/*
 * Copyright (c) 2018 - 2028. www.vtuzx.com Inc. All Rights Reserved
 */
package com.vtuzx.kingdee.xqc_api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.vtuzx.core.VtuzxException;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.bean.dto.VtuzxPage;
import com.vtuzx.core.constant.IVtuzxConst;
import com.vtuzx.core.file.excel.VtuzxExcel;
import com.vtuzx.core.file.excel.VtuzxExcelSheet;
import com.vtuzx.core.utils.VtuzxUtil;
import com.vtuzx.kingdee.xqc_core.bean.VtuzxArrayList;
import com.vtuzx.kingdee.xqc_core.bean.kingdee.VtuzxKingdeeCloudClient;
import com.vtuzx.kingdee.xqc_core.bean.xqc.BillMaterial;
import com.vtuzx.kingdee.xqc_core.bean.xqc.BillMaterialBox;
import com.vtuzx.kingdee.xqc_core.constant.BillEvent;
import com.vtuzx.kingdee.xqc_core.constant.BillType;
import com.vtuzx.kingdee.xqc_core.constant.IXqcConst;
import com.vtuzx.kingdee.xqc_core.service.IJiKeYunApiService;
import com.vtuzx.kingdee.xqc_api.service.IJiKeYunService;
import com.vtuzx.kingdee.xqc_core.dao.*;
import com.vtuzx.kingdee.xqc_core.service.IVtuzxBasicService;
import com.vtuzx.kingdee.xqc_core.service.IVtuzxCoreInventoryService;
import com.vtuzx.kingdee.xqc_core.service.IVtuzxKingdeeService;
import com.vtuzx.kingdee.xqc_core.service.impl.VtuzxBasicServiceImpl;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.StringOperators;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class JiKeYunServiceImpl implements IJiKeYunService {

    @Autowired
    IJiKeYunApiService jiKeYunApiService;
    @Autowired
    StoreTokenDao storeTokenDao;
    @Autowired
    PrdInDetailDao prdInDetailDao;

    @Autowired
    PrdInDetailBoxDao prdInDetailBoxDao;

    @Autowired
    CollectionDao collectionDao;

    @Autowired
    private BainianAllocationDao bainianAllocationDao;

    /**
     * Logger
     */
    private static final Logger _logger = LoggerFactory.getLogger(VtuzxBasicServiceImpl.class);

    @Autowired
    PaymentDao paymentDao;

    @Autowired
    private IVtuzxKingdeeService kingdeeService;

    @Autowired
    private InnersettorderDao innersettorderDao;

    @Autowired
    private StorageOutDao storageOutDao;

    @Autowired
    private SaleOutDao saleOutDao;

    @Autowired
    private MaterialDao materialDao;

    @Autowired
    private SaleOutDetailDao saleOutDetailDao;

    @Autowired
    private PriceListDao priceListDao;

    @Autowired
    private TraceabilityCodeDetailDao traceabilityCodeDetailDao;

    @Autowired
    private CoreParamDao paramDao;

    /**
     * 即时库存
     */
    @Autowired
    private InventoryDao inventoryDao;

    /**
     * 即时库存
     */
    @Autowired
    private InventoryDetailDao inventoryDetailDao;


    @Autowired
    private IVtuzxBasicService basicService;

    @Autowired
    private IVtuzxCoreInventoryService coreInventoryService;

    @Autowired
    private AllocationDao allocationDao;

    @Autowired
    private JikeyunAllocationDao jikeyunAllocationDao;

    @Autowired
    private JikeyunSaleDao jikeyunSaleDao;

    @Autowired
    private PriceListLogDao priceListLogDao;


    @Autowired
    private SyncOrderDao syncOrderDao;

    @Autowired
    private ChannelDao channelDao;

    @Autowired
    private SyncDao syncDao;

    @Autowired
    private SyncTaskDao syncTaskDao;

    @Autowired
    private SyncTaskHistoryDao syncTaskHistoryDao;

    @Autowired
    private SelfProductDao selfProductDao;

    @Autowired
    private WarehouseDao warehouseDao;

    @Autowired
    private SelfProductBillDao selfProductBillDao;

    @Autowired
    private YXCustomerDao yxCustomerDao;

    @Autowired
    private JikeyunChannelCustomerDao jikeyunChannelCustomerDao;

    @Autowired
    private SyncTimeDao syncTimeDao;

    @Autowired
    private GoodsPackageDao goodsPackageDao;

    public static final Set<String> YEXIANG_WAREHOUSECODE;
    static {
        Set<String> codeSet_YEXIANG_WAREHOUSECODE = new HashSet<>(Arrays.asList(
                "XQWZ00002", "YXQH000004", "XQBB00031", "0009", "YXBB000022",
                "YXBB000017", "YXBB000021", "YXBB000018", "YXBB000020", "YXBB000019",
                "YXBB000010", "YXBB000008", "YXBB000009", "YXBB000003", "YXBB000004",
                "YXBB000006", "YXBB000007", "YXBB000005", "YXBB000002", "YXBB000001"
        ));
        YEXIANG_WAREHOUSECODE = Collections.unmodifiableSet(codeSet_YEXIANG_WAREHOUSECODE);
    }

    public static final Set<String> CHANNEL_WAREHOUSECODE;
    static {
        Set<String> codeSet_CHANNEL_WAREHOUSECODE = new HashSet<>(Arrays.asList(
                "XQBB00071", "XQBB00069", "HZGN", "XQBB00075", "XQWG0036", "YXWB01"
        ));
        CHANNEL_WAREHOUSECODE = Collections.unmodifiableSet(codeSet_CHANNEL_WAREHOUSECODE);
    }

    @Override
    public VtuzxMap getPaymentList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String billNo = VtuzxUtil.getString(param, "billNo");
        String billNum = VtuzxUtil.getString(param, "billNum");
        String bankAccountName = VtuzxUtil.getString(param, "bankAccountName");//账户类型
        String settAccName = VtuzxUtil.getString(param, "settAccName");//账户名称
        String companyName = VtuzxUtil.getString(param, "companyName");//账户名称
        String shopName = VtuzxUtil.getString(param, "shopName");//销售渠道
        List<String> createTime = VtuzxUtil.getObject(param, "createTime");
        String createUsername = VtuzxUtil.getString(param, "createUserName");
        String tranName = VtuzxUtil.getString(param, "tranName");
        String isUpload = VtuzxUtil.getString(param, "isUpload");
        Criteria cond = new Criteria();
        //晓芹公司的
        cond.and("companyName").regex("晓芹");
        if (!VtuzxUtil.isEmpty(billNo)) {
            cond.and("billNo").regex(billNo);
        }
        if (!VtuzxUtil.isEmpty(bankAccountName)) {
            cond.and("bankAccountName").regex(bankAccountName);
        }
//        if(!VtuzxUtil.isEmpty(companyName)){
//            cond.and("companyName").regex(companyName);
//        }
        if (!VtuzxUtil.isEmpty(settAccName)) {
            cond.and("settAccName").regex(settAccName);
        }
        if (!VtuzxUtil.isEmpty(shopName)) {
            cond.and("shopName").regex(shopName);
        }
        if (!VtuzxUtil.isEmpty(billNum)) {
            cond.and("billNum").regex(billNum);
        }
        if (!VtuzxUtil.isEmpty(createUsername)) {
            cond.and("createUsername").regex(createUsername);
        }
        if (!VtuzxUtil.isEmpty(tranName)) {
            cond.and("tranName").regex(tranName);
        }
        if (!VtuzxUtil.isEmpty(isUpload)) {
            cond.and("isUpload").is(isUpload);
        }
        if (!VtuzxUtil.isEmpty(createTime)) {
            cond.and("createTime").gte(VtuzxUtil.parseDate(createTime.get(0))).lte(VtuzxUtil.parseDate(createTime.get(1) + " 23:59:59"));
        }

        VtuzxPage page = paymentDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("billNum", VtuzxUtil.getString(doc, "billNum"))//极客云单据号
                .append("billNo", VtuzxUtil.getString(doc, "billNo"))
                .append("companyName", VtuzxUtil.getString(doc, "companyName"))
                .append("createTime", VtuzxUtil.formatYmdHmsF(VtuzxUtil.getObject(doc, "createTime")))
                .append("createUserName", VtuzxUtil.getString(doc, "createUsername"))
                .append("tranName", VtuzxUtil.getString(doc, "tranName"))
                .append("isUpload", VtuzxUtil.getString(doc, "isUpload"))
                .append("unitName", VtuzxUtil.getString(doc, "unitName"))
                .append("bankAccountName", VtuzxUtil.getString(doc, "bankAccountName"))//账户类型
                .append("settAccName", VtuzxUtil.getString(doc, "settAccName"))//结算账户，（账户名称）
                .append("shopName", VtuzxUtil.getString(doc, "shopName"))//销售渠道
                .append("unitTypeName", VtuzxUtil.getString(doc, "unitTypeName"))
                .append("recInCuValue", VtuzxUtil.getInt(doc, "recInCuValue")));

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public VtuzxMap uploadKingdeePayment(ObjectId userId, List<String> billNoList) throws Exception {
        Iterator<Document> paymentItr = paymentDao.findList(Criteria.where("billNum").in(billNoList), null, 0, 0);
        List<Document> paymentList = new ArrayList<>();
        while (paymentItr.hasNext()) {
            Document payDoc = paymentItr.next();
            paymentList.add(payDoc);
        }
        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
        VtuzxKingdeeCloudClient YXclient = kingdeeService.loginKingdeeYeXiang();
        //如果付款单是客户退款，传金蝶收款退款单，其它的还是传金蝶付款单
        for (Document paymentDoc : paymentList) {
            String billNum = VtuzxUtil.getString(paymentDoc, "billNum");
            String companyName = VtuzxUtil.getString(paymentDoc, "companyName");
            Document historyDoc = syncOrderDao.findOne(Criteria.where("billNo").is(billNum));
            ObjectId id = null;
            if (historyDoc == null) {
                historyDoc = new Document("billNo", billNum);
            } else {
                id = VtuzxUtil.getObject(historyDoc, "_id");
            }
            historyDoc.append("billNo", billNum);
            historyDoc.append("userId", userId);
            historyDoc.append("userName", "userName");
            historyDoc.append("source", "source");
            historyDoc.append("data", paymentDoc);
            historyDoc.append("event", "jackYunPayment");
            //付款单
            try {
                if (companyName.contains("晓芹")) {
//                   syncKingdeePayment(client,paymentDoc,historyDoc);
                } else if (companyName.contains("野象")) {
                    syncKingdeePayment(YXclient, paymentDoc, historyDoc);
                }

                historyDoc.append("success", true);
                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    historyDoc.remove("message");
                    historyDoc.append("updateUserId", userId);
                    historyDoc.append("updateUserName", "userName");
                    syncOrderDao.updateById(id, historyDoc);
                }
                String _id = VtuzxUtil.getString(paymentDoc, "_id");
                paymentDao.updateById(_id, new Document("isUpload", "yes"));
            } catch (Exception e) {
                historyDoc.append("prdInStockStock", false).append("message", e.getMessage()).append("success", false);
                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    syncOrderDao.updateById(id, historyDoc);
                }
                throw new VtuzxException(e.getMessage());
            }

        }
        return new VtuzxMap("isUpload", true);
    }


    @Override
    public VtuzxMap getCollectionList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String billNo = VtuzxUtil.getString(param, "billNo");
        String billNum = VtuzxUtil.getString(param, "billNum");
        String bankAccountName = VtuzxUtil.getString(param, "bankAccountName");//账户类型
        String settAccName = VtuzxUtil.getString(param, "settAccName");//账户名称
        String companyName = VtuzxUtil.getString(param, "companyName");//公司名称
        String shopName = VtuzxUtil.getString(param, "shopName");//销售渠道
        List<String> createTime = VtuzxUtil.getObject(param, "createTime");
        String createUsername = VtuzxUtil.getString(param, "createUserName");
        String tranName = VtuzxUtil.getString(param, "tranName");
        String isUpload = VtuzxUtil.getString(param, "isUpload");
        Criteria cond = new Criteria();
        //晓芹公司的
        cond.and("companyName").regex("晓芹");
        if (!VtuzxUtil.isEmpty(billNo)) {
            cond.and("billNo").regex(billNo);
        }
        if (!VtuzxUtil.isEmpty(bankAccountName)) {
            cond.and("bankAccountName").regex(bankAccountName);
        }
//        if(!VtuzxUtil.isEmpty(companyName)){
//            cond.and("companyName").regex(companyName);
//        }
        if (!VtuzxUtil.isEmpty(settAccName)) {
            cond.and("settAccName").regex(settAccName);
        }
        if (!VtuzxUtil.isEmpty(shopName)) {
            cond.and("shopName").regex(shopName);
        }
        if (!VtuzxUtil.isEmpty(billNum)) {
            cond.and("billNum").regex(billNum);
        }
        if (!VtuzxUtil.isEmpty(createUsername)) {
            cond.and("createUsername").regex(createUsername);
        }
        if (!VtuzxUtil.isEmpty(tranName)) {
            cond.and("tranName").regex(tranName);
        }
        if (!VtuzxUtil.isEmpty(isUpload)) {
            cond.and("isUpload").is(isUpload);
        }
        if (!VtuzxUtil.isEmpty(createTime)) {
            cond.and("createTime").gte(VtuzxUtil.parseDate(createTime.get(0))).lte(VtuzxUtil.parseDate(createTime.get(1) + " 23:59:59"));
        }

        VtuzxPage page = collectionDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("billNum", VtuzxUtil.getString(doc, "billNum"))//极客云单据号
                .append("billNo", VtuzxUtil.getString(doc, "billNo"))
                .append("companyName", VtuzxUtil.getString(doc, "companyName"))
                .append("createTime", VtuzxUtil.formatYmdHmsF(VtuzxUtil.getObject(doc, "createTime")))
                .append("createUserName", VtuzxUtil.getString(doc, "createUsername"))
                .append("tranName", VtuzxUtil.getString(doc, "tranName"))
                .append("isUpload", VtuzxUtil.getString(doc, "isUpload"))
                .append("unitName", VtuzxUtil.getString(doc, "unitName"))
                .append("bankAccountName", VtuzxUtil.getString(doc, "bankAccountName"))//账户类型
                .append("settAccName", VtuzxUtil.getString(doc, "settAccName"))//结算账户，（账户名称）
                .append("shopName", VtuzxUtil.getString(doc, "shopName"))//销售渠道
                .append("unitTypeName", VtuzxUtil.getString(doc, "unitTypeName"))
                .append("recInCuValue", VtuzxUtil.getInt(doc, "recInCuValue")));

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public VtuzxMap uploadKingdeeCollection(ObjectId userId, String userName, List<String> billNoList) throws Exception {
        Iterator<Document> collectionItr = collectionDao.findList(Criteria.where("billNum").in(billNoList), null, 0, 0);
        List<Document> collectionlist = new ArrayList<>();
        while (collectionItr.hasNext()) {
            Document collDoc = collectionItr.next();
            collectionlist.add(collDoc);
        }
        VtuzxKingdeeCloudClient YXclint = kingdeeService.loginKingdeeYeXiang();
        for (Document collectionDoc : collectionlist) {
            String billNum = VtuzxUtil.getString(collectionDoc, "billNum");
            String companyName = VtuzxUtil.getString(collectionDoc, "companyName");
            Document historyDoc = syncOrderDao.findOne(Criteria.where("billNo").is(billNum));
            ObjectId id = null;
            if (historyDoc == null) {
                historyDoc = new Document("billNo", billNum);
            } else {
                id = VtuzxUtil.getObject(historyDoc, "_id");
            }
            historyDoc.append("billNo", billNum);
            historyDoc.append("userId", userId);
            historyDoc.append("userName", userName);
            historyDoc.append("source", "source");
            historyDoc.append("data", collectionDoc);
            historyDoc.append("event", "jackYunCollection");
            //收款单
            try {
                if (companyName.contains("晓芹")) {
//                    syncKingdeeCollection(client,collectionDoc,historyDoc);
                } else if (companyName.contains("野象")) {
                    syncKingdeeCollection(YXclint, collectionDoc, historyDoc);
                }

                historyDoc.append("success", true);
                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    historyDoc.remove("message");
                    historyDoc.append("updateUserId", userId);
                    historyDoc.append("updateUserName", userName);
                    syncOrderDao.updateById(id, historyDoc);
                }
                String _id = VtuzxUtil.getString(collectionDoc, "_id");
                collectionDao.updateById(_id, new Document("isUpload", "yes"));
            } catch (Exception e) {
                historyDoc.append("prdInStockStock", false).append("message", e.getMessage()).append("success", false);
                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    syncOrderDao.updateById(id, historyDoc);
                }
//                throw new VtuzxException(e.getMessage());
                _logger.info(e.getMessage());
            }

        }
        return new VtuzxMap("isUpload", true);
    }

    @Override
    public void uploadKingdeeBill(ObjectId userId, String userName, Map<String, Object> param) throws VtuzxException {
        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
        VtuzxKingdeeCloudClient clientYX = kingdeeService.loginKingdeeYX();
        List<String> billNoList = new ArrayList<>();
        List<String> materialNoList = new ArrayList<>();
        VtuzxMap saleOutDataMap = new VtuzxMap();
        Iterator<Document> saleOutItr = saleOutDao.findList(Criteria.where("billNo").in(billNoList), null, 0, 0);
        while (saleOutItr.hasNext()) {
            Document saleOutDoc = saleOutItr.next();
            String billNo = VtuzxUtil.getString(saleOutDoc, "billNo");
            String materialNo = VtuzxUtil.getString(saleOutDoc, "materialNo");
            materialNoList.add(materialNo);
            billNoList.add(billNo);
            saleOutDataMap.append(billNo, saleOutDoc);
        }

        VtuzxMap materialMap = new VtuzxMap();
        Iterator<Document> materialItr = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materialItr.hasNext()) {
            Document mtr = materialItr.next();
            VtuzxMap mtrMap = new VtuzxMap();
            String materialNumber = VtuzxUtil.getString(mtr, "fNumber");
            String materialName = VtuzxUtil.getString(mtr, "fName");
            String fSpecification = VtuzxUtil.getString(mtr, "fSpecification");
            String fBaseUnitIdFName = VtuzxUtil.getString(mtr, "fBaseUnitIdFName");
            mtrMap.append("materialName", materialName);
            mtrMap.append("materialSpec", fSpecification);
            mtrMap.append("unit", fBaseUnitIdFName);
            mtrMap.append("materialNo", materialNumber);
            materialMap.append(materialNumber, mtrMap);
        }
        Iterator<Document> saleOutDetailItr = saleOutDetailDao.findList(Criteria.where("billNo").in(billNoList), null, 0, 0);
        while (saleOutDetailItr.hasNext()) {
            Document saleOutDetailDoc = saleOutDetailItr.next();
            VtuzxMap saleOutDetailMap = new VtuzxMap(saleOutDetailDoc);
            String billNo = VtuzxUtil.getString(saleOutDetailDoc, "billNo");
            Document saleOutDoc = VtuzxUtil.getObject(saleOutDataMap, billNo);
            if (!VtuzxUtil.isEmpty(saleOutDoc)) {
                List<VtuzxMap> saleOutDetailList = VtuzxUtil.getObject(saleOutDoc, "saleOutDetailList");
                if (VtuzxUtil.isEmpty(saleOutDetailList)) {
                    List<VtuzxMap> list = new ArrayList<>();
                    list.add(saleOutDetailMap);
                    saleOutDoc.append("saleOutDetailList", list);
                } else {
                    saleOutDetailList.add(saleOutDetailMap);
                }
            }
        }

        saleOutDataMap.forEach((k, v) -> {
            Document saleOutDoc = (Document) v;
            String org = VtuzxUtil.getString(saleOutDoc, "org");
            String sellerMemo = VtuzxUtil.getString(saleOutDoc, "sellerMemo");
            String billNo = VtuzxUtil.getString(saleOutDoc, "billNo");
            String billType = VtuzxUtil.getString(saleOutDoc, "billType");
            List<VtuzxMap> saleOutDetailList = VtuzxUtil.getObject(saleOutDoc, "saleOutDetailList");
            if ("xq".equals(org)) {
                if (billType.contains("saleReturn")) {
                    try {
                        syncKingdeeSaleReturn(client, saleOutDetailList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (billType.contains("saleOut")) {
                    try {
                        syncKingdeeSaleOut(client, materialMap, saleOutDetailList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (billType.contains("otherOut")) {
                    Map<String, Object> map = new LinkedHashMap<>();
                    map.put("billNo", billNo);
                    map.put("sellerMemo", sellerMemo);
                    try {
                        syncKingdeeOtherOut(client, saleOutDetailList, materialMap, map);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (billType.contains("collectionRefund")) {

                } else if (billType.contains("sale")) {
                    try {
                        syncKingdeeSaleBill(client, saleOutDetailList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                if (billType.contains("saleReturn")) {
                    try {
                        syncKingdeeSaleReturn(clientYX, saleOutDetailList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (billType.contains("saleOut")) {
                    try {
                        syncKingdeeSaleOut(clientYX, materialMap, saleOutDetailList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (billType.contains("otherOut")) {
                    Map<String, Object> map = new LinkedHashMap<>();
                    map.put("billNo", billNo);
                    map.put("sellerMemo", sellerMemo);
                    try {
                        syncKingdeeOtherOut(clientYX, saleOutDetailList, materialMap, map);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (billType.contains("collectionRefund")) {

                } else if (billType.contains("sale")) {
                    try {
                        syncKingdeeSaleBill(clientYX, saleOutDetailList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });


    }

    public VtuzxMap getParameters(Map<String, Object> param) {
        List<String> keys = VtuzxUtil.getObject(param, "keys");
        Iterator<Document> docList = paramDao.findList(Criteria.where("key").in(keys).and("effect").is(true), (Document) null, 0, 0);
        VtuzxMap retMap = new VtuzxMap();
        while (docList.hasNext()) {
            Document doc = docList.next();
            VtuzxMap data = new VtuzxMap();
            String key = VtuzxUtil.getString(doc, "key");
            data.put("key", key);
            data.put("name", VtuzxUtil.getString(doc, "name"));
            data.put("value", VtuzxUtil.getString(doc, "value"));
            retMap.put(key, data);
        }
        return retMap;
    }


    //金蝶销售订单
    private void syncKingdeeSaleBill(VtuzxKingdeeCloudClient client, List<VtuzxMap> saleOrderList) throws Exception {
        Map<String, Object> saleOutOrderParam = new LinkedHashMap<>();
        Map<String, Object> saleOutOrderModel = new LinkedHashMap<>();
        List<Map<String, Object>> fSaleOutEntry = new ArrayList<>();
        Map<String, Object> saleOutMap = new LinkedHashMap<>();
        for (VtuzxMap sale : saleOrderList) {
            String materialNo = VtuzxUtil.getString(sale, "materialNo");
            double taxRate = VtuzxUtil.getDouble(sale, materialNo);
            String stockNo = VtuzxUtil.getString(sale, "stockNo");
            String unit = VtuzxUtil.getString(sale, "unit");
            String batchNo = VtuzxUtil.getString(sale, "batchNo");
            double count = VtuzxUtil.getDouble(sale, "count");
            saleOutMap.put("FRowType", "Standard");
            saleOutMap.put("FMaterialID", new VtuzxMap("FNumber", materialNo));
            saleOutMap.put("FUnitID", new VtuzxMap("FNumber", unit));
            saleOutMap.put("FLot", new VtuzxMap("FNumber", batchNo));
            saleOutMap.put("FRealQty", count);
            saleOutMap.put("FIsFree", false);
            saleOutMap.put("FOwnerTypeID", "BD_OwnerOrg");
            saleOutMap.put("FOwnerID", new VtuzxMap("FNumber", "100"));
            saleOutMap.put("FEntryTaxRate", taxRate);
            saleOutMap.put("FStockID", new VtuzxMap("FNumber", stockNo));
            saleOutMap.put("FStockStatusID", new VtuzxMap("FNumber", "KCZT01_SYS"));
            saleOutMap.put("FSalUnitID", new VtuzxMap("FNumber", unit));
            saleOutMap.put("FSALUNITQTY", count);
            saleOutMap.put("FSALBASEQTY", count);
            saleOutMap.put("FPRICEBASEQTY", count);
            saleOutMap.put("FOUTCONTROL", false);
            saleOutMap.put("FIsOverLegalOrg", false);
            saleOutMap.put("FARNOTJOINQTY", count);
            saleOutMap.put("FCheckDelivery", false);
            fSaleOutEntry.add(saleOutMap);
        }

        saleOutOrderModel.put("FBillTypeID", new VtuzxMap("FNUMBER", "XSCKD01_SYS"));
//        saleOutOrderModel.put("FDate", createTime);
        saleOutOrderModel.put("FSaleOrgId", new VtuzxMap("FNumber", "100"));
        saleOutOrderModel.put("FCustomerID", new VtuzxMap("FNumber", "01.00001"));
        saleOutOrderModel.put("FStockOrgId", new VtuzxMap("FNumber", "100"));
        saleOutOrderModel.put("FReceiverID", new VtuzxMap("FNumber", "01.00001"));
        saleOutOrderModel.put("FSettleID", new VtuzxMap("FNumber", "01.00001"));
        saleOutOrderModel.put("FPayerID", new VtuzxMap("FNumber", "01.00001"));
        saleOutOrderModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");
        saleOutOrderModel.put("FIsTotalServiceOrCost", false);
        saleOutOrderModel.put("FEntity", fSaleOutEntry);

        saleOutOrderParam.put("NeedUpDateFields", new ArrayList<>());
        saleOutOrderParam.put("NeedReturnFields", new ArrayList<>());
        saleOutOrderParam.put("IsDeleteEntry", true);
        saleOutOrderParam.put("SubSystemId", "");
        saleOutOrderParam.put("IsVerifyBaseDataField", false);
        saleOutOrderParam.put("IsEntryBatchFill", true);
        saleOutOrderParam.put("ValidateFlag", true);
        saleOutOrderParam.put("NumberSearch", true);
        saleOutOrderParam.put("InterationFlags", "");
        saleOutOrderParam.put("Model", saleOutOrderModel);
        List<VtuzxMap> outStockBillList = kingdeeService.save(client, "SAL_OUTSTOCK", saleOutOrderParam);
        VtuzxMap outStockMap = outStockBillList.get(0);
        String number = VtuzxUtil.getString(outStockMap, "Number");
        kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
        kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
    }

    //金蝶销售出
    private void syncKingdeeSaleOut(VtuzxKingdeeCloudClient client, VtuzxMap data, List<VtuzxMap> dataList) throws Exception {
        String customerCode = VtuzxUtil.getString(data,"customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data,"customerName");//客户名称

        //查询客户
        String customerId = getCustomer(customerCode, client, null,customerName);
        String warehouseName = VtuzxUtil.getString(data,"warehouseName");//仓库名称(吉客云销售渠道)
        String shopName = VtuzxUtil.getString(data,"shopName");//店铺名称
        if("bb044山东路专卖店-野象".equals(shopName)){
            shopName = "bb045山东路专卖店-野象";
        }
        //外埠的不要做截取，野象-展示厅不要截取，天猫的不要做截取
        if (shopName.contains("-") && !shopName.contains("外埠") && !shopName.startsWith("bb") && !shopName.contains("展示厅") && !shopName.contains("天猫") && !shopName.startsWith("百年晓芹")){
            shopName = shopName.substring(0,shopName.indexOf("-"));
        }
        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        //如果查询不到销售渠道

        String channelGroup = VtuzxUtil.getString(channelDoc,"channelGroup");//渠道分组(销售渠道)
        String tradeNo = VtuzxUtil.getString(data,"tradeNo");//销售单号

        List<Map<String,Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data,"tradeOrderAssemblyGoodsDtoList");//组合装信息
        double otherFee = VtuzxUtil.getDouble(data,"otherFee");//销售费用
        double discountFee = VtuzxUtil.getDouble(data,"discountFee");//整单优惠
        double couponFee = VtuzxUtil.getDouble(data,"couponFee");//平台补贴(平台优惠)
        String sellerMemo = VtuzxUtil.getString(data,"sellerMemo");//备注(客服备注)
        String buyerMemo = VtuzxUtil.getString(data,"buyerMemo");//(买家备注)客户备注
        String appendMemo = VtuzxUtil.getString(data,"appendMemo");//追加备注
        String onlineTradeNo = VtuzxUtil.getString(data,"onlineTradeNo");//网店订单号
        String seller = VtuzxUtil.getString(data,"seller");//业务员
        String flagNames = VtuzxUtil.getString(data,"flagNames");//标记名称
        String createTime = VtuzxUtil.getString(data,"gmtCreate");//创建日期
//        Date consignTime = VtuzxUtil.getObject(data,"consignTime");//发货日期
        String invoiceStatus = VtuzxUtil.getString(data,"invoiceStatus");//是否开票
        //同步数据时会同步部门,后加的
        String departName = VtuzxUtil.getString(data,"departName");//部门
        String salesManId = "";
        if(!VtuzxUtil.isEmpty(seller)){
            //如果部门没同步下来的话
            if (VtuzxUtil.isEmpty(departName)){
                departName = getMainDepartName(seller, null);//吉客云部门名称
            }
            salesManId = getSellId(seller,client);//金蝶业务员id
        }


        //渠道是爱你商城传金蝶部门为市场部，客户为爱你商城
        if("爱你商城".equals(shopName)){
            departName = "市场部";
        } else if (shopName.startsWith("外埠")){
            departName = shopName;
        }

        if (departName.contains("外埠")){//如果部门为外埠固定传(因为吉客云和金蝶部门名称没统一)
            departName = "外埠（营销外埠）";
        } else if (departName.contains("网购") || departName.contains("营销三部")){
            departName = "网购（营销网购）";
        } else if (departName.contains("bb044")){
            departName = "bb045山东路专卖店";
        } else if (departName.contains("本埠（二）")){
            departName = "bb047比优特三八广场店";
        } else if (departName.contains("客服部")){
            departName = "客户信息服务部";
        }
        //查询部门的时候加上禁用状态
        String deliveryDeptId = "";//发货部门id
        String qdNo = "";//渠道编码
        if(!VtuzxUtil.isEmpty(departName)){//如果吉客云部门名称不为空，查询金蝶部门id
            //查询发货部门id
            String cond = String.format("FName = '%s' and FForbidStatus ='%s'", departName,"A");
            List<VtuzxMap> bd_department = kingdeeService.query(client, "BD_Department", new VtuzxArrayList<>(
                    "FNumber",//=部门编码
                    "FNAME"//部门
            ), cond);
            if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                deliveryDeptId = (String) bd_department.get(0).get("FNumber");
            }

            //查询客户外埠的根据客户查询，其他的根据部门查询
            if (departName.startsWith("外埠")){
                String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", customerName,"A");
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                        "FNumber",//客户编码
                        "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                        "FNAME"//客户名称
                ), cusCond);
                if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                    qdNo = VtuzxUtil.getString(bd_customer.get(0), "F_SXLJ_xsqd.FNUMBER");
                }
            } else {
                String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", departName,"A");
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                        "FNumber",//客户编码
                        "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                        "FNAME"//客户名称
                ), cusCond);
                if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                    qdNo = VtuzxUtil.getString(bd_customer.get(0), "F_SXLJ_xsqd.FNUMBER");
                }
            }

        }


        //如果发货部门为空的话不让传
//        if(VtuzxUtil.isEmpty(deliveryDeptId)){
//            historyDoc.append("message","无法查询到部门,请维护");
//            return "无法查询到部门,请维护";
//        }

        //在同步单据的时候会查询仓库id
        //存在没有仓库的情况,给与提示
        String stockId = VtuzxUtil.getString(data,"stockId");
//        if(VtuzxUtil.isEmpty(stockId)){
//            historyDoc.append("message","没有获取到仓库id,请重新同步单据");
//            return "没有获取到仓库id,请重新同步单据";
//        }
        //查询客户(门店通过部门查询客户，其他的通过渠道查询)
        String shopCustomerId = "";
        if(shopName.startsWith("bb")){
            shopCustomerId = getCustomerShopName(client,departName);
        } else{
            //添加门店渠道中的对应关系
            if("野象考拉店铺".equals(shopName)){
                shopName = "网易考拉";
            } else if ("野象苏宁超市".equals(shopName)){
                shopName = "苏宁超市";
            } else if ("客服外卖-代收货款".equals(shopName)){
                shopName = "客服外卖";
            } else if ("野象-展示厅".equals(shopName)){
                shopName = "展示厅";
            } else if("天猫超市-野象".equals(shopName)){
                shopName = "天猫超市";
            } else if ("客服外卖".equals(shopName)){
                shopName = "客户信息服务部";
            } else if ("特渠库".equals(shopName)){
                shopName = "客户信息服务部";
            } else if("杭州光年有限公司".equals(shopName)){
                shopName = "光年（杭州）水产品";
            } else if ("天猫旗舰店-野象".equals(shopName)){
                shopName = "天猫商城";
            } else if ("百年晓芹-拼多多生鲜".equals(shopName)){
                shopName = "拼多多-生鲜";
            }
            shopCustomerId = getCustomerShopName(client,shopName);
        }
        List<Map<String,Object>> goodsList = VtuzxUtil.getObject(data,"goodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSCKD01_SYS"));//单据类型 标准销售出库单
        payModel.put("FDate", createTime);//单据日期

//        payModel.put("FDate",VtuzxUtil.formatYmdHmsF(new Date()));
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织

        //如果是外埠的客户还是正常客户
        if("外埠".equals(channelGroup) || shopName.startsWith("外埠")){
            payModel.put("FCustomerID", new Document("FNumber", customerId));//客户
            payModel.put("FReceiverID", new Document("FNumber", customerId));//收货方
            payModel.put("FStockOrgId", new Document("FNumber", "200"));//发货组织(200)
            payModel.put("FSettleID", new Document("FNumber", customerId));//结算方
            payModel.put("FPayerID", new Document("FNumber", customerId));//付款方
        } else {//其他的传渠道信息,渠道是特渠库也传客户
            if ("特渠库".equals(shopName)){
                payModel.put("FCustomerID", new Document("FNumber", customerId));//客户
                payModel.put("FReceiverID", new Document("FNumber", customerId));//收货方
                payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织(200)
                payModel.put("FSettleID", new Document("FNumber", customerId));//结算方
                payModel.put("FPayerID", new Document("FNumber", customerId));//付款方
            } else {
                payModel.put("FCustomerID",new Document("FNumber", shopCustomerId));//渠道
                payModel.put("FReceiverID",new Document("FNumber", shopCustomerId));//收货方
                if(shopName.startsWith("bb")){
                    payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织(200)
                } else {
                    payModel.put("FStockOrgId", new Document("FNumber", "200"));//发货组织(200)
                }
//                payModel.put("FStockOrgId", new Document("FNumber", "200"));//发货组织(200)
                payModel.put("FSettleID",new Document("FNumber", shopCustomerId));//结算方
                payModel.put("FPayerID",new Document("FNumber", shopCustomerId));//付款方
            }

        }

        payModel.put("FDeliveryDeptID",new Document("FNumber","01"));//发货部门
        payModel.put("FSaleDeptID",new Document("FNumber",deliveryDeptId));//销售部门
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FCDateOffsetValue",0);//创建日期
        payModel.put("FIsTotalServiceOrCost", false);//整单服务或费用
        payModel.put("F_PSUH_XSDH",tradeNo);//吉客云销售单号
        payModel.put("F_ora_disFee",discountFee);//整单优惠
        payModel.put("F_ora_appendMemo",appendMemo);//追加备注
        payModel.put("F_ora_saleFee",otherFee);//销售费用
//        payModel.put("F_ora_kefuMemo",sellerMemo);//客服备注
        payModel.put("F_ora_kehuMemo",buyerMemo);//客户备注
        payModel.put("F_ora_lineTradeNo",onlineTradeNo);//网店订单号
        payModel.put("F_PSUH_biaoji",flagNames);//标记
        payModel.put("F_PSUH_couponFee",couponFee);//平台补贴
        payModel.put("F_PSUH_XSQD",channelGroup);//销售渠道
        payModel.put("F_PSUH_DPMC",shopName);//店铺名称
        payModel.put("F_PSUH_KH",customerName);//客户名称
        payModel.put("F_SXLJ_JKYKHBH",customerCode);//客户编号
        //如果是3的话为开票成功，其他为未开票
        if ("3".equals(invoiceStatus)){
            payModel.put("F_PSUH_SFKP",true);//是否开票
        } else {
            payModel.put("F_PSUH_SFKP",false);//是否开票
        }

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FIsIncludedTax", true);//是否含税
        SubHeadEntity.put("FLocalCurrID", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        SubHeadEntity.put("FIsPriceExcludeTax", true);//价外税
        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        //循环货品集合，添加金蝶单据体信息
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String,Object> materialMap = arrangeMaterial(goodsList,tradeOrderAssemblyGoodsDtoList,materialNoList);
        Map<String,Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String,Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList),null,0,0);
        while (materials.hasNext()){
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc,"fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc,"fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc,"fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc,"fBaseUnitIdFName");//单位名称
            String substring = "";
            if(fTaxRateName.startsWith("零")){
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }

            taxMap.put(materialNo,Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName,fBaseUnitIdNumber);
        }
        //添加单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "SellTotal");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        String unit = (String) unitMap.get(unitName);
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        //金蝶单价为0就是赠品
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", skuCount);//实发数量
                        colMap.put("FTaxPrice", settPrice / skuCount);//含税单价
                        //单价是0就是赠品
                        if(settPrice == 0){
                            colMap.put("FIsFree", true);//是否赠品
                        } else {
                            colMap.put("FIsFree", false);//是否赠品
                        }

                        colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型

                        double tax = (Double) taxMap.get(goodsNo);//获取税率

                        if (shopName.startsWith("bb")){
                            colMap.put("FOWNERID", new Document("FNumber", "100"));//货主
                            colMap.put("FKeeperID", new Document("FNumber", "100"));//保管者
                            colMap.put("FStockId", new Document("FNumber",stockId));//仓库
                        } else {
                            colMap.put("FOWNERID", new Document("FNumber", "200"));//货主
                            colMap.put("FKeeperID", new Document("FNumber", "200"));//保管者
                            colMap.put("FStockId", new Document("FNumber","001"));//仓库
                        }
                        colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                        colMap.put("FEntroynote",goodsMemo);//货品备注
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSALUNITQTY", skuCount);//销售数量
                        colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                        colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                        colMap.put("FOUTCONTROL", false);//控制出库数量
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                        colMap.put("FCheckDelivery", false);//发货检验
                        colMap.put("F_PSUH_QD", new Document("FNumber",qdNo));
                        FEntity.add(colMap);

                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee");//分摊后金额,对应金蝶含税单价
                double skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String unit = (String) unitMap.get(unitName);

                Map<String, Object> colMap = new LinkedHashMap<>();
                //金蝶单价为0就是赠品
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", skuCount);//实发数量
                colMap.put("FTaxPrice", settPrice / skuCount);//含税单价 = 分摊后金额 / 数量
                //单价是0就是赠品
                if(settPrice == 0){
                    colMap.put("FIsFree", true);//是否赠品
                } else {
                    colMap.put("FIsFree", false);//是否赠品
                }

                colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型

                //colMap.put("FEntryTaxRate", tax);//税率
                if (shopName.startsWith("bb")){
                    colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                    colMap.put("FKeeperID", new Document("FNumber", "100"));//保管者
                    colMap.put("FStockId", new Document("FNumber",stockId));//仓库
                } else {
                    colMap.put("FOWNERID", new Document("FNumber", "200"));//货主开发销售测试
                    colMap.put("FKeeperID", new Document("FNumber", "200"));//保管者
                    colMap.put("FStockId", new Document("FNumber","001"));//仓库
                }

                colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                colMap.put("FEntroynote",goodsMemo);//货品备注
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSALUNITQTY", skuCount);//销售数量
                colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                colMap.put("FOUTCONTROL", false);//控制出库数量
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                colMap.put("FCheckDelivery", false);//发货检验
                colMap.put("F_PSUH_QD", new Document("FNumber",qdNo));
                FEntity.add(colMap);
            }
        }

        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", true);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);


        String number = "";
        //创建销售出库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_OUTSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
//            number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
//            kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
//            kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
//            historyDoc.append("kingdeeNumber",number);
        } catch (Exception e) {
            _logger.info(e.getMessage());

        }
    }

    //金蝶销售出Task
    private void syncKingdeeSaleOutTask(VtuzxKingdeeCloudClient client, Document data, VtuzxMap materialMap, List<Document> dataList, Document historyDoc, VtuzxMap FID) throws Exception {
        Map<String, Object> saleOutOrderParam = new LinkedHashMap<>();
        Map<String, Object> saleOutOrderModel = new LinkedHashMap<>();
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        List<Map<String, Object>> fSaleOutEntry = new ArrayList<>();
        for (Document saleOut : dataList) {
            Document doc = new Document(saleOut);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if(isFit == 1){
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for(Map<String, Object> fitOrder: tradeOrderAssemblyGoodsDtoList){
                    String tradeSubTradeId = VtuzxUtil.getString(fitOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        Map<String, Object> saleOutMap = new LinkedHashMap<>();
                        String goodsNo = VtuzxUtil.getString(fitOrder, "goodsNo");
                        String GoodsNo = VtuzxUtil.getString(fitOrder, "GoodsNo");
                        //组合装物料编码集合
                        List<String> fitMaterialNoList = new ArrayList<>();
                        for(Map<String, Object> tradeOrderList: tradeOrderAssemblyGoodsDtoList) {
                            //组合装编号
                            String fitPackageGoodNo = VtuzxUtil.getString(tradeOrderList, "GoodsNo");
                            if (!fitMaterialNoList.contains(fitPackageGoodNo)) {
                                fitMaterialNoList.add(fitPackageGoodNo);
                            }
                        }
                        String fitGoodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                        //获取组合装信息
                        Document fitGoodsPackage = goodsPackageDao.findOne(Criteria.where("goodsNo").is(fitGoodsNo));
                        //组合装货品信息
                        List<Map<String, Object>> goodsPackageDetailList = VtuzxUtil.getObject(fitGoodsPackage, "goodsPackageDetail");
                        //将goodsPackageDetailList转换为Map, key:物料编码, value:分摊比例
                        Map<String, Integer> goodsNoToShareRatioMap = new HashMap<>();
                        for (Map<String, Object> pkg : goodsPackageDetailList) {
                            String packageGoodsNo = (String) pkg.get("goodsNo");
                            Integer shareRatio = (Integer) pkg.get("shareRatio");
                            goodsNoToShareRatioMap.put(packageGoodsNo, shareRatio);
                        }
                        //Map<String, Object> priceMap = VtuzxUtil.getObject(FID, "priceMap");
                        String unit = "";
                        double taxRate = 0.0;
                        double price = 0.0;
                        //double priceSale = 0.0;
                        double count = 0.0;
                        //double shareFavourableAfterFee = 0.0;
                        double sellPrice = 0.0;
                        //调拨单
                        //组合装物料编码集合
                        if (VtuzxUtil.isEmpty(VtuzxUtil.getString(fitOrder, "GoodsNo"))) {
                            List<String> fitMaterialNoListAllocation = new ArrayList<>();//组合装物料编码集合
                            if (!fitMaterialNoListAllocation.contains(goodsNo)) {
                                fitMaterialNoListAllocation.add(goodsNo);
                            }
                            //查询价目表获取价格信息
                            Iterator<Document> fitPriceItr = priceListDao.findList(Criteria.where("materialNo").in(fitMaterialNoListAllocation), null, 0, 0);
                            Map<String, Object> fitPriceMap = new HashMap<>();//key : 物料编码 val:初始供货价
                            while (fitPriceItr.hasNext()) {
                                Document fitPriceDoc = fitPriceItr.next();
                                String materialNo = VtuzxUtil.getString(fitPriceDoc, "materialNo");
                                Double currentPrice = VtuzxUtil.getDouble(fitPriceDoc, "currentPrice");
                                fitPriceMap.put(materialNo, currentPrice);
                            }
                            price = (double) fitPriceMap.get(goodsNo);
                            VtuzxMap materialDoc = VtuzxUtil.getObject(materialMap, goodsNo);
                            taxRate = VtuzxUtil.getDouble(materialDoc, "taxRate");
                            unit = VtuzxUtil.getString(materialDoc, "unit");
                            count = VtuzxUtil.getDouble(fitOrder, "skuCount");
                            //销售单
                        } else{
                            Iterator<Document> fitPriceItr = priceListDao.findList(Criteria.where("materialNo").in(fitMaterialNoList), null, 0, 0);
                            Map<String, Object> fitPriceRatioMap = new HashMap<>();//key : 物料编码 val:分摊比例
                            while (fitPriceItr.hasNext()) {
                                Document fitPriceDoc = fitPriceItr.next();
                                String fitMaterialNo = VtuzxUtil.getString(fitPriceDoc, "materialNo");
                                int priceRatio = goodsNoToShareRatioMap.get(fitMaterialNo);
                                fitPriceRatioMap.put(fitMaterialNo, priceRatio);
                            }
                            int shareRatio = (int) fitPriceRatioMap.get(GoodsNo);
                            sellPrice = VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee") * shareRatio;
                            //VtuzxMap materialDocSale = VtuzxUtil.getObject(materialMap, GoodsNo);
                            taxRate = VtuzxUtil.getDouble(fitOrder, "TaxRate");
                            unit = VtuzxUtil.getString(fitOrder, "Unit");
                            count = VtuzxUtil.getDouble(fitOrder, "SellCount");
                        }
                        String unitId = "";
                        //查询单位编码
                        String cond = String.format("Fname = '%s'", unit);
                        List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                                "FNumber",
                                "FNAME"
                        ), cond);
                        if (bd_customer != null && bd_customer.size() > 0) {
                            unitId = bd_customer.get(0).getString("FNumber");
                        }
                        saleOutMap.put("FRowType", "Standard");
                        if (VtuzxUtil.isEmpty(GoodsNo)) {
                            saleOutMap.put("FMaterialID", new VtuzxMap("FNumber", goodsNo));
                        } else if (VtuzxUtil.isEmpty(goodsNo)) {
                            saleOutMap.put("FMaterialID", new VtuzxMap("FNumber", GoodsNo));
                        } else {
                            _logger.info("GOODSNO为空");
                        }
                        saleOutMap.put("FUnitID", new VtuzxMap("FNumber", unitId));
                        saleOutMap.put("FRealQty", count);
                        if (VtuzxUtil.isEmpty(GoodsNo)) {
                            if (price == 0) {
                                saleOutMap.put("FIsFree", true);//是否赠品
                            } else {
                                saleOutMap.put("FIsFree", false);//是否赠品
                            }
                        } else if (VtuzxUtil.isEmpty(goodsNo)) {
                            //单价是0就是赠品
                            if (sellPrice/count == 0) {
                                saleOutMap.put("FIsFree", true);//是否赠品
                            } else {
                                saleOutMap.put("FIsFree", false);//是否赠品
                            }
                        } else {
                            _logger.info("单据错误");
                        }
                        saleOutMap.put("FOwnerTypeID", "BD_OwnerOrg");
                        String flagForFOwnerID = VtuzxUtil.getString(FID, "flagForFOwnerID");
                        saleOutMap.put("FOwnerID", new Document("FNumber", flagForFOwnerID));
//                        saleOutMap.put("FEntryTaxRate", taxRate);
                        String flagForFStockID = VtuzxUtil.getString(FID, "flagForFStockID");
                        saleOutMap.put("FStockID", new Document("FNumber", flagForFStockID));//仓库
                        if (sellPrice == 0.0) {
                            saleOutMap.put("FTaxPrice", price);
                        } else if (price == 0.0) {
                            saleOutMap.put("FTaxPrice", sellPrice/count);
                            String flagForFSaledeptid = VtuzxUtil.getObject(FID, "flagForFSaledeptid");
                            saleOutMap.put("FSaledeptid", new VtuzxMap("FNumber", flagForFSaledeptid));//销售部门
                        } else {
                            _logger.info("PRICE为空");
                        }
                        saleOutMap.put("FStockStatusID", new VtuzxMap("FNumber", "KCZT01_SYS"));
                        saleOutMap.put("FSalUnitID", new VtuzxMap("FNumber", unitId));
                        saleOutMap.put("FSALUNITQTY", count);
                        saleOutMap.put("FSALBASEQTY", count);
                        saleOutMap.put("FPRICEBASEQTY", count);
                        saleOutMap.put("FOUTCONTROL", false);
                        saleOutMap.put("FIsOverLegalOrg", false);
                        saleOutMap.put("FARNOTJOINQTY", count);
                        saleOutMap.put("FCheckDelivery", false);
                        fSaleOutEntry.add(saleOutMap);
                    }
                }
            } else{
                Map<String, Object> saleOutMap = new LinkedHashMap<>();
                String goodsNo = VtuzxUtil.getString(saleOut, "goodsNo");
                String GoodsNo = VtuzxUtil.getString(saleOut, "GoodsNo");
                Map<String, Object> priceMap = VtuzxUtil.getObject(FID, "priceMap");
                String unit = "";
                double taxRate = 0.0;
                double price = 0.0;
                //double priceSale = 0.0;
                double count = 0.0;
                //double shareFavourableAfterFee = 0.0;
                double sellPrice = 0.0;
                //调拨单
                if (VtuzxUtil.isEmpty(GoodsNo)) {
                    //价目表价格（初始供货价）
                    price = (double) priceMap.get(goodsNo);
                    VtuzxMap materialDoc = VtuzxUtil.getObject(materialMap, goodsNo);
                    taxRate = VtuzxUtil.getDouble(materialDoc, "taxRate");
                    unit = VtuzxUtil.getString(materialDoc, "unit");
                    count = VtuzxUtil.getDouble(saleOut, "skuCount");
                    //销售单
                } else if (VtuzxUtil.isEmpty(goodsNo)) {
                    //priceSale = (double) priceMap.get(GoodsNo);
                    //shareFavourableAfterFee = VtuzxUtil.getDouble(saleOut, "ShareFavourableAfterFee");
                    //sellPrice = VtuzxUtil.getDouble(saleOut, "SellPrice");
                    sellPrice = VtuzxUtil.getDouble(saleOut, "ShareFavourableAfterFee");
                    VtuzxMap materialDocSale = VtuzxUtil.getObject(materialMap, GoodsNo);
                    taxRate = VtuzxUtil.getDouble(saleOut, "TaxRate");
                    unit = VtuzxUtil.getString(saleOut, "Unit");
                    count = VtuzxUtil.getDouble(saleOut, "SellCount");
                } else {
                    _logger.info("GOODSNO为空");
                }
                String unitId = "";
                //查询单位编码
                String cond = String.format("Fname = '%s'", unit);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",
                        "FNAME"
                ), cond);
                if (bd_customer != null && bd_customer.size() > 0) {
                    unitId = bd_customer.get(0).getString("FNumber");
                }

                //===获取金蝶物料单位===
                String floatCond = String.format("FNumber = '%s' or FNumber = '%s' ", goodsNo, GoodsNo);
                List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FBaseUnitId.FNumber"
                ), floatCond);
                if (bd_Material != null && bd_Material.size() > 0) {
                    unitId = bd_Material.get(0).getString("FBaseUnitId.FNumber");
                }
                //===获取金蝶物料单位===

                saleOutMap.put("FRowType", "Standard");
                if (VtuzxUtil.isEmpty(GoodsNo)) {
                    saleOutMap.put("FMaterialID", new VtuzxMap("FNumber", goodsNo));
                } else if (VtuzxUtil.isEmpty(goodsNo)) {
                    saleOutMap.put("FMaterialID", new VtuzxMap("FNumber", GoodsNo));
                } else {
                    _logger.info("GOODSNO为空");
                }
                saleOutMap.put("FUnitID", new VtuzxMap("FNumber", unitId));
                saleOutMap.put("FRealQty", count);
                //调拨单
                if (VtuzxUtil.isEmpty(GoodsNo)) {
                    //单价是0就是赠品
                    if (price == 0) {
                        saleOutMap.put("FIsFree", true);//是否赠品
                    } else {
                        saleOutMap.put("FIsFree", false);//是否赠品
                    }
                    // 销售单
                } else if (VtuzxUtil.isEmpty(goodsNo)) {
                    //单价是0就是赠品
                    if (sellPrice/count == 0) {
                        saleOutMap.put("FIsFree", true);//是否赠品
                    } else {
                        saleOutMap.put("FIsFree", false);//是否赠品
                    }
                } else {
                    _logger.info("单据错误");
                }
                saleOutMap.put("FOwnerTypeID", "BD_OwnerOrg");
                String flagForFOwnerID = VtuzxUtil.getString(FID, "flagForFOwnerID");
                saleOutMap.put("FOwnerID", new Document("FNumber", flagForFOwnerID));
//                saleOutMap.put("FEntryTaxRate", taxRate);
                String flagForFStockID = VtuzxUtil.getString(FID, "flagForFStockID");
                saleOutMap.put("FStockID", new Document("FNumber", flagForFStockID));//仓库
                //调拨单
                if (VtuzxUtil.isEmpty(GoodsNo)) {
                    saleOutMap.put("FTaxPrice", price);
                    //销售单
                } else if (VtuzxUtil.isEmpty(goodsNo)) {
                    saleOutMap.put("FTaxPrice", sellPrice/count);
                    String flagForFSaledeptid = VtuzxUtil.getObject(FID, "flagForFSaledeptid");
                    saleOutMap.put("FSaledeptid", new VtuzxMap("FNumber", flagForFSaledeptid));//销售部门
                } else {
                    _logger.info("GOODSNO为空");
                }
                saleOutMap.put("FStockStatusID", new VtuzxMap("FNumber", "KCZT01_SYS"));
                saleOutMap.put("FSalUnitID", new VtuzxMap("FNumber", unitId));
                saleOutMap.put("FSALUNITQTY", count);
                saleOutMap.put("FSALBASEQTY", count);
                saleOutMap.put("FPRICEBASEQTY", count);
                saleOutMap.put("FOUTCONTROL", false);
                saleOutMap.put("FIsOverLegalOrg", false);
                saleOutMap.put("FARNOTJOINQTY", count);
                saleOutMap.put("FCheckDelivery", false);
                fSaleOutEntry.add(saleOutMap);
            }
        }
        //销售单情况
        if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "allocateNo"))) {//调拨单号为空
            String customerCode = VtuzxUtil.getString(data, "customerCode");//吉客云客户编号
            String shopName = VtuzxUtil.getString(data, "shopName");//销售渠道、店铺名称
            String JKYDH = VtuzxUtil.getString(data, "tradeNo");//吉客云销售单号
            double discountFee = VtuzxUtil.getDouble(data, "discountFee");//整单优惠
            String appendMemo = VtuzxUtil.getString(data, "appendMemo");//追加备注
            String sellerMemo = VtuzxUtil.getString(data, "sellerMemo");//客服备注
            double otherFee = VtuzxUtil.getDouble(data, "otherFee");//销售费用
            String onlineTradeNo = VtuzxUtil.getString(data, "onlineTradeNo");//网店单号
            String buyerMemo = VtuzxUtil.getString(data, "buyerMemo");//客户备注
            String flagNames = VtuzxUtil.getString(data, "flagNames");//标记
            double couponFee = VtuzxUtil.getDouble(data, "couponFee");//平台补贴
            String tradeTime = VtuzxUtil.getString(data, "tradeTime");//下单时间
            String createTime = VtuzxUtil.getString(data, "gmtCreate");//创建日期
            String flagForBillChannel = VtuzxUtil.getString(FID, "flagForBillChannel");//结算渠道
            saleOutOrderModel.put("F_SXLJ_JKYKHBH", customerCode);//吉客云客户编号
            saleOutOrderModel.put("F_PSUH_XSQD", shopName);//销售渠道
            saleOutOrderModel.put("F_PSUH_XSDH", JKYDH);//吉客云销售单号
            saleOutOrderModel.put("F_PSUH_JSDH", "--");//吉客云结算单号
            saleOutOrderModel.put("F_ora_disFee", discountFee);//整单优惠
            if (VtuzxUtil.isEmpty(appendMemo)) {
                saleOutOrderModel.put("F_ora_appendMemo", "--");//追加备注为空
            } else {
                saleOutOrderModel.put("F_ora_appendMemo", appendMemo);//追加备注
            }
            if (VtuzxUtil.isEmpty(sellerMemo)) {
                saleOutOrderModel.put("F_ora_kefuMemo", "--");//客服备注为空
            } else {
                saleOutOrderModel.put("F_ora_kefuMemo", sellerMemo);//客服备注
            }
            saleOutOrderModel.put("F_ora_saleFee", otherFee);//销售费用
            if (VtuzxUtil.isEmpty(onlineTradeNo)) {
                saleOutOrderModel.put("F_ora_lineTradeNo", "--");//网店单号为空
            } else {
                saleOutOrderModel.put("F_ora_lineTradeNo", onlineTradeNo);//网店单号
            }
            //saleOutOrderModel.put("F_PSUH_KD",points);//扣点
            if (VtuzxUtil.isEmpty(buyerMemo)) {
                saleOutOrderModel.put("F_ora_kehuMemo", "--");//客户备注为空
            } else {
                saleOutOrderModel.put("F_ora_kehuMemo", buyerMemo);//客户备注
            }
            if (VtuzxUtil.isEmpty(flagNames)) {
                saleOutOrderModel.put("F_PSUH_biaoji", "--");//标记为空
            } else {
                saleOutOrderModel.put("F_PSUH_biaoji", flagNames);//标记
            }
            saleOutOrderModel.put("F_PSUH_DPMC", shopName);//店铺名称
            saleOutOrderModel.put("F_PSUH_couponFee", couponFee);//平台补贴
            saleOutOrderModel.put("F_PSUH_XDSJ", tradeTime);//下单时间
            saleOutOrderModel.put("F_PSUH_JSQD", new Document("FNumber", flagForBillChannel));//结算渠道
            //如果是寄存的单据,下单时间和创建时间在同月是正常销售单,不是同月的加一个寄存标记(为了不用算钱)
            if (flagNames.contains("寄存")) {
                if (!VtuzxUtil.isEmpty(tradeTime)) {
                    String createSub = createTime.substring(5, 7);//创建日期月份
                    String tradeSub = tradeTime.substring(5, 7);//下单日期月份
                    if (!createSub.equals(tradeSub)) {
                        saleOutOrderModel.put("F_PSUH_JCBJ", "寄存");//寄存标记
                    }
                }
            } else {
                saleOutOrderModel.put("F_PSUH_JCBJ", "--");//寄存标记为空
            }
            //调拨单情况
        } else if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "tradeNo"))) {//销售单号为空
            String JKYDH = VtuzxUtil.getString(data, "allocateNo");//吉客云调拨单号
            saleOutOrderModel.put("F_PSUH_XSDH", "--");//吉客云销售单号
            saleOutOrderModel.put("F_PSUH_JSDH", JKYDH);//吉客云结算单号
        }
        saleOutOrderModel.put("FBillTypeID", new VtuzxMap("FNUMBER", "XSCKD01_SYS"));
        saleOutOrderModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));
        String flagForFRetcustId = VtuzxUtil.getString(FID, "flagForFRetcustId");
        saleOutOrderModel.put("FRetcustId", new Document("FNumber", flagForFRetcustId));
        String flagForFSaleOrgId = VtuzxUtil.getString(FID, "flagForFSaleOrgId");
        saleOutOrderModel.put("FSaleOrgId", new Document("FNumber", flagForFSaleOrgId));
        saleOutOrderModel.put("FCorrespondOrgId", new Document("FNumber", flagForFSaleOrgId));
        String flagForFSaleDeptID = VtuzxUtil.getString(FID, "flagForFSaleDeptID");
        saleOutOrderModel.put("FSaleDeptID", new Document("FNumber", flagForFSaleDeptID));
        String flagForFCustomerID = VtuzxUtil.getString(FID, "flagForFCustomerID");
        saleOutOrderModel.put("FCustomerID", new Document("FNumber", flagForFCustomerID));
        String flagForFStockOrgId = VtuzxUtil.getString(FID, "flagForFStockOrgId");
        saleOutOrderModel.put("FStockOrgId", new Document("FNumber", flagForFStockOrgId));
        String flagForFReceiverID = VtuzxUtil.getString(FID, "flagForFReceiverID");
        saleOutOrderModel.put("FReceiverID", new Document("FNumber", flagForFReceiverID));
        String flagForFSettleID = VtuzxUtil.getString(FID, "flagForFSettleID");
        saleOutOrderModel.put("FSettleID", new Document("FNumber", flagForFSettleID));
        String flagForFPayerID = VtuzxUtil.getString(FID, "flagForFPayerID");
        saleOutOrderModel.put("FPayerID", new Document("FNumber", flagForFPayerID));
        saleOutOrderModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");
        saleOutOrderModel.put("FIsTotalServiceOrCost", false);
        saleOutOrderModel.put("FEntity", fSaleOutEntry);
        saleOutOrderParam.put("NeedUpDateFields", new ArrayList<>());
        saleOutOrderParam.put("NeedReturnFields", new ArrayList<>());
        saleOutOrderParam.put("IsDeleteEntry", true);
        saleOutOrderParam.put("SubSystemId", "");
        saleOutOrderParam.put("IsVerifyBaseDataField", false);
        saleOutOrderParam.put("IsEntryBatchFill", true);
        saleOutOrderParam.put("ValidateFlag", true);
        saleOutOrderParam.put("NumberSearch", true);
        saleOutOrderParam.put("InterationFlags", "");
        saleOutOrderParam.put("Model", saleOutOrderModel);
        String number = "";
        historyDoc.append("param", new VtuzxMap("SAL_OUTSTOCK", saleOutOrderParam));
        try {
            List<VtuzxMap> outStockBillList = kingdeeService.save(client, "SAL_OUTSTOCK", saleOutOrderParam);
            VtuzxMap outStockMap = outStockBillList.get(0);
            number = VtuzxUtil.getString(outStockMap, "Number");
            kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
            historyDoc.append("syncTask", true);
        } catch (Exception e) {
            if (e.getMessage().contains("更新库存不成功")) {//如果因为库存原因没有上传成功做一个其他入库后再审核
                VtuzxMap FIDOther = new VtuzxMap();
                String flagForFStockID = VtuzxUtil.getString(FID, "flagForFStockID");
                if (Objects.equals(flagForFSaleOrgId, "200")) {
                    FIDOther.append("flagOtherForFSTOCKID", flagForFStockID)
                            .append("flagOtherForFStockOrgId", flagForFStockOrgId)
                            .append("flagOtherForFSUPPLIERID", "05.0002");
                } else if (Objects.equals(flagForFSaleOrgId, "100")) {
                    FIDOther.append("flagOtherForFSTOCKID", flagForFStockID)
                            .append("flagOtherForFStockOrgId", flagForFStockOrgId)
                            .append("flagOtherForFSUPPLIERID", "05.0002");
                } else {
                    throw new VtuzxException(e.getMessage());
                }
                Exception recoveryException = null;
                try {
                    syncKingdeeOtherInBillTask(client, data, FIDOther);
                    kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
                    historyDoc.append("kingdeeNumber", number);
                    historyDoc.append("syncTask", true);
                } catch (Exception ex) {
                    recoveryException = ex;
                }
                //如果其他入库单异常
                if (recoveryException != null) {
                    VtuzxException finalException = new VtuzxException("库存更新失败，且创建其他入库单仍异常: " + recoveryException.getMessage());
                    finalException.initCause(e);
                    throw finalException;
                }
            } else {
                //如果不是更新库存不成功的异常,直接抛出
                throw new VtuzxException(e.getMessage());
            }
        }
    }

    //金蝶其他出
    private void syncKingdeeOtherOut(VtuzxKingdeeCloudClient client, List<VtuzxMap> dataList, VtuzxMap materialMap, Map<String, Object> trade) throws Exception {
        String billNo = VtuzxUtil.getString(trade, "tradeNo");
        String remark = VtuzxUtil.getString(trade, "sellerMemo");
        VtuzxMap outStockParam = new VtuzxMap();
        VtuzxMap outStockModel = new VtuzxMap();
        List<Map<String, Object>> fOutStockEntry = new ArrayList<>();
        for (Map<String, Object> material : dataList) {
            String materialNo = VtuzxUtil.getString(material, "materialNo");
            Document materialDoc = VtuzxUtil.getObject(materialMap, materialNo);
            boolean isBatchManage = VtuzxUtil.getBoolean(materialDoc, "isBatchManage");
            String unit = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");
            String stockNo = VtuzxUtil.getString(material, "stockNo");
            String batchNo = VtuzxUtil.getString(material, "batchNo");
            double count = Math.abs(VtuzxUtil.getDouble(material, "count"));

            Map<String, Object> detailMap = new LinkedHashMap<>();
            detailMap.put("FMaterialId", new VtuzxMap("FNumber", materialNo));
            detailMap.put("FUnitID", new VtuzxMap("FNumber", unit));
            detailMap.put("FBaseUnitId", new VtuzxMap("FNumber", unit));
            detailMap.put("FStockId", new VtuzxMap("FNumber", stockNo));
            if (isBatchManage) {
                detailMap.put("FLot", new VtuzxMap("FNumber", batchNo));
            }
            detailMap.put("FOwnerTypeId", "BD_OwnerOrg");
            detailMap.put("FOwnerId", new VtuzxMap("FNumber", "100"));
            detailMap.put("FStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            detailMap.put("FKeeperId", new VtuzxMap("FNumber", "100"));
            detailMap.put("FKeeperTypeId", "BD_KeeperOrg");
            detailMap.put("FQty", count);
            fOutStockEntry.add(detailMap);
        }
        outStockModel.append("FEntity", fOutStockEntry)
                .append("FBillTypeID", new VtuzxMap("FNumber", "QTCKD01_SYS"))
                .append("FStockOrgId", new VtuzxMap("FNumber", "100"))
                .append("FPickOrgId", new VtuzxMap("FNumber", "100"))
                .append("FStockDirect", "GENERAL")
                .append("FDate", VtuzxUtil.formatYmdF(new Date()))
                .append("FOwnerTypeIdHead", "BD_OwnerOrg")
                .append("FOwnerIdHead", new VtuzxMap("FNumber", "100"))
                .append("FBaseCurrId", new VtuzxMap("FNumber", "PRE001"))
                .append("FDeptId", new VtuzxMap("FNumber", "01.01"))
                .append("FNOTE", remark)
                .append("F_qtckd_ZTDJH", billNo)
                .append("F_qtckd_CZRY", "吉克云自动同步")
                .append("F_qtckd_FHR", "吉克云自动同步")
                .append("F_qtckd_SJLY", "吉克云自动同步")
                .append("F_qtckd_ZTYWRQ", VtuzxUtil.formatYmdF(new Date()));

        outStockParam.append("model", outStockModel);
        List<VtuzxMap> stkOutStockList = kingdeeService.save(client, "STK_MisDelivery", outStockParam);
        VtuzxMap stkOutStockMap = stkOutStockList.get(0);
        String number = VtuzxUtil.getString(stkOutStockMap, "Number");
        kingdeeService.submit(client, "STK_MisDelivery", "0", number);
        kingdeeService.audit(client, "STK_MisDelivery", "0", number, "STK_InvCheckResult");
    }

    //金蝶销售退
    private void syncKingdeeSaleReturn(VtuzxKingdeeCloudClient client, List<VtuzxMap> dataList) throws Exception {
        //销售退
        Map<String, Object> saleModel = new LinkedHashMap<>();//销售退model
        saleModel.put("FID", 0);//实体主键
        saleModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型标准销售退货单
        saleModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));//单据日期
        saleModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        saleModel.put("FRetcustId", new Document("FNumber", "CUST0041"));//退货客户先固定野象
        saleModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        saleModel.put("FStockOrgId", new Document("FNumber", "100"));//库存组织
        saleModel.put("FReceiveCustId", new Document("FNumber", "CUST0041"));//收货方先固定野象
        saleModel.put("FSettleCustId", new Document("FNumber", "CUST0041"));//结算方先固定野象
        saleModel.put("FPayCustId", new Document("FNumber", "CUST0041"));//付款方先固定野象
        saleModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        saleModel.put("FIsTotalServiceOrCost", false);//整单服务标识

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        SubHeadEntity.put("FSettleOrgId", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率

        List<Map<String, Object>> FEntity = new ArrayList<>();
        for (Map<String, Object> goods : dataList) {
            String goodsNo = VtuzxUtil.getString(goods, "materialNo");//货品编号

            double taxRate = VtuzxUtil.getDouble(goods, "taxRate");//税率
            double settPrice = VtuzxUtil.getDouble(goods, "settPrice");//结算单价
            String unitName = VtuzxUtil.getString(goods, "unitName");
            int skuCount = VtuzxUtil.getInt(goods, "skuCount");

            //查询单位编码
            String cond = String.format("Fname = '%s'", unitName);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                    "FNumber",
                    "FNAME"
            ), cond);
            String unit = "";
            if (bd_customer != null && bd_customer.size() > 0) {
                unit = bd_customer.get(0).getString("FNumber");
            }
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
            colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
            colMap.put("FRealQty", skuCount);//实退数量
            colMap.put("FTaxPrice", settPrice);//含税单价
            colMap.put("FIsFree", false);//是否赠品
            colMap.put("FEntryTaxRate", taxRate);//税率
            colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
            colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
            colMap.put("FOwnerId", new Document("FNumber", "100"));//货主
            colMap.put("FStockId", new Document("FNumber", "YX001"));//仓库 先固定野象001
            colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态

            colMap.put("FLot", new Document("FNumber", "88888"));//批号

            colMap.put("FDeliveryDate", VtuzxUtil.formatYmdHmsF(new Date()));//退货日期
            colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
            colMap.put("FSalUnitQty", skuCount);//销售数量
            colMap.put("FSalBaseQty", skuCount);//销售基本数量
            colMap.put("FPriceBaseQty", skuCount);//计价基本数量
            colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
            colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
            colMap.put("FIsReturnCheck", false);//退货校验
            FEntity.add(colMap);
        }
        saleModel.put("SubHeadEntity", SubHeadEntity);
        saleModel.put("FEntity", FEntity);

        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", false);
        kneeParam.put("IsEntryBatchFill", true);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", saleModel);

        List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", kneeParam);
        VtuzxMap kingdeeCustomerMap = customerList.get(0);
        String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
        kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
        kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
    }

    //金蝶销售退Task
    private void syncKingdeeSaleReturnTask(VtuzxKingdeeCloudClient client, Document data, List<Document> dataList, Document historyDoc, VtuzxMap FID) throws Exception {
        //销售退
        Map<String, Object> saleModel = new LinkedHashMap<>();//销售退model
        saleModel.put("FID", 0);//实体主键
        saleModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型标准销售退货单
        saleModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));//单据日期
        String flagForFSaleOrgId = VtuzxUtil.getObject(FID, "flagForFSaleOrgId");
        saleModel.put("FSaleOrgId", new VtuzxMap("FNumber", flagForFSaleOrgId));//销售组织
        String flagForFRetcustId = VtuzxUtil.getObject(FID, "flagForFRetcustId");
        saleModel.put("FRetcustId", new VtuzxMap("FNumber", flagForFRetcustId));//退货客户
        saleModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        String flagForFStockOrgId = VtuzxUtil.getObject(FID, "flagForFStockOrgId");
        saleModel.put("FStockOrgId", new VtuzxMap("FNumber", flagForFStockOrgId));//库存组织
        String flagForFReceiveCustId = VtuzxUtil.getObject(FID, "flagForFReceiveCustId");
        saleModel.put("FReceiveCustId", new VtuzxMap("FNumber", flagForFReceiveCustId));//收货方
        String flagForFSettleCustId = VtuzxUtil.getObject(FID, "flagForFSettleCustId");
        saleModel.put("FSettleCustId", new VtuzxMap("FNumber", flagForFSettleCustId));//结算方
        String flagForFPayCustId = VtuzxUtil.getObject(FID, "flagForFPayCustId");
        saleModel.put("FPayCustId", new VtuzxMap("FNumber", flagForFPayCustId));//付款方
        String flagForFCustomerID = VtuzxUtil.getObject(FID, "flagForFCustomerID");
        saleModel.put("FCustomerID", new VtuzxMap("FNumber", flagForFCustomerID));
        String flagForFReceiverID = VtuzxUtil.getObject(FID, "flagForFReceiverID");
        saleModel.put("FReceiverID", new VtuzxMap("FNumber", flagForFReceiverID));
        String flagForFSettleID = VtuzxUtil.getObject(FID, "flagForFSettleID");
        saleModel.put("FSettleID", new VtuzxMap("FNumber", flagForFSettleID));
        String flagForFPayerID = VtuzxUtil.getObject(FID, "flagForFPayerID");
        saleModel.put("FPayerID", new VtuzxMap("FNumber", flagForFPayerID));
        String flagForFOwnerIdHead = VtuzxUtil.getObject(FID, "flagForFOwnerIdHead");
        saleModel.put("FOwnerIdHead", new VtuzxMap("FNumber", flagForFOwnerIdHead));
        saleModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        saleModel.put("FIsTotalServiceOrCost", false);//整单服务标识
        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        String flagForFSettleOrgId = VtuzxUtil.getObject(FID, "flagForFSettleOrgId");
        SubHeadEntity.put("FSettleOrgId", new VtuzxMap("FNumber", flagForFSettleOrgId));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        String flagForFStockID = VtuzxUtil.getObject(FID, "flagForFStockID");
        SubHeadEntity.put("FStockID", new VtuzxMap("FNumber", flagForFStockID));//仓库
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        List<Map<String, Object>> FEntity = new ArrayList<>();
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        String goodsNo;
        double taxRate;
        double price;
        String unitName;
        int skuCount;
//        double shareFavourableAfterFee = 0.0;
        Map<String, Object> priceMap = VtuzxUtil.getObject(FID, "priceMap");
        for (Map<String, Object> goods : dataList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> fitOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(fitOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        if (VtuzxUtil.isEmpty(VtuzxUtil.getString(fitOrder, "TradeId"))) {
                            goodsNo = VtuzxUtil.getString(fitOrder, "goodsNo");//货品编号
                            taxRate = VtuzxUtil.getDouble(fitOrder, "taxRate");//税率
//                settPrice = VtuzxUtil.getDouble(fitOrder,"settPrice");//结算单价
                            price = (double) priceMap.get(goodsNo);//含税单价
                            unitName = VtuzxUtil.getString(fitOrder, "unitName");
                            skuCount = VtuzxUtil.getInt(fitOrder, "skuCount");
                        } else {
                            goodsNo = VtuzxUtil.getString(fitOrder, "GoodsNo");//货品编号
                            taxRate = VtuzxUtil.getDouble(fitOrder, "TaxRate");//税率
//                settPrice = VtuzxUtil.getDouble(fitOrder, "SellPrice");//结算单价
                            unitName = VtuzxUtil.getString(fitOrder, "Unit");
//                settPrice = VtuzxUtil.getDouble(fitOrder, "ShareFavourableAfterFee");
//                settPrice = VtuzxUtil.getDouble(fitOrder, "SellPrice");
//                price = (double) priceMap.get(goodsNo);
//                price = VtuzxUtil.getDouble(fitOrder, "SellPrice");//含税单价
                            price = VtuzxUtil.getDouble(fitOrder, "ShareFavourableAfterFee");//含税单价
                            skuCount = VtuzxUtil.getInt(fitOrder, "SellCount");
                        }
                        //查询单位编码
                        String cond = String.format("Fname = '%s'", unitName);
                        List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                                "FNumber",
                                "FNAME"
                        ), cond);
                        String unit = "";
                        if (bd_customer != null && bd_customer.size() > 0) {
                            unit = bd_customer.get(0).getString("FNumber");
                        }
                        //判断是否启用批号
                        String floatCond = String.format("FNumber = '%s'", goodsNo);
                        List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                "FIsBatchManage","FBaseUnitId.FNumber"
                        ), floatCond);
                        //获取单位编码
                        boolean flag = true;
                        if (bd_Material != null && bd_Material.size() > 0) {
                            flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                            unit = bd_Material.get(0).getString("FBaseUnitId.FNumber");
                        }
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");//产品类型
                        String flagForFSaledeptid = VtuzxUtil.getObject(FID, "flagForFSaledeptid");
                        colMap.put("FSaledeptid", new VtuzxMap("FNumber", flagForFSaledeptid));//销售部门
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
                        colMap.put("FRealQty", Math.abs(skuCount));//实退数量
                        colMap.put("FTaxPrice", Math.abs(price / skuCount));//含税单价
                        if (price == 0) {
                            colMap.put("FIsFree", true);//是否赠品
                        } else {
                            colMap.put("FIsFree", false);//是否赠品
                        }
                        colMap.put("FBaseunitQty", Math.abs(skuCount));//库存基本数量
//                        colMap.put("FEntryTaxRate", taxRate);//税率
                        colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                        colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                        String flagForFOwnerId = VtuzxUtil.getObject(FID, "flagForFOwnerId");
                        colMap.put("FOwnerId", new Document("FNumber", flagForFOwnerId));//货主
                        String flagForFOWNERID = VtuzxUtil.getObject(FID, "flagForFOWNERID");
                        colMap.put("FOWNERID", new VtuzxMap("FNumber", flagForFOWNERID));//货主
                        String flagForFOwnerID = VtuzxUtil.getObject(FID, "flagForFOwnerID");
                        colMap.put("FOwnerID", new VtuzxMap("FNumber", flagForFOwnerID));//货主
                        colMap.put("FStockID", new VtuzxMap("FNumber", flagForFStockID));//仓库
                        colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                        if (flag) {
                            colMap.put("FLot", new Document("FNumber", "88888"));//批号
                        }
                        colMap.put("FDeliveryDate", VtuzxUtil.formatYmdHmsF(new Date()));//退货日期
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSalUnitQty", Math.abs(skuCount));//销售数量
                        colMap.put("FSalBaseQty", Math.abs(skuCount));//销售基本数量
                        colMap.put("FPriceBaseQty", Math.abs(skuCount));//计价基本数量
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", Math.abs(skuCount));//未关联应收数量（计价单位
                        colMap.put("FIsReturnCheck", false);//退货校验
                        FEntity.add(colMap);
                    }
                }
            } else {
                if (VtuzxUtil.isEmpty(VtuzxUtil.getString(goods, "TradeId"))) {
                    goodsNo = VtuzxUtil.getString(goods, "goodsNo");//货品编号
                    taxRate = VtuzxUtil.getDouble(goods, "taxRate");//税率
//                settPrice = VtuzxUtil.getDouble(goods,"settPrice");//结算单价
                    price = (double) priceMap.get(goodsNo);//含税单价
                    unitName = VtuzxUtil.getString(goods, "unitName");
                    skuCount = VtuzxUtil.getInt(goods, "skuCount");
                } else {
                    goodsNo = VtuzxUtil.getString(goods, "GoodsNo");//货品编号
                    taxRate = VtuzxUtil.getDouble(goods, "TaxRate");//税率
//                settPrice = VtuzxUtil.getDouble(goods, "SellPrice");//结算单价
                    unitName = VtuzxUtil.getString(goods, "Unit");
//                settPrice = VtuzxUtil.getDouble(goods, "ShareFavourableAfterFee");
//                settPrice = VtuzxUtil.getDouble(goods, "SellPrice");
//                price = (double) priceMap.get(goodsNo);
//                price = VtuzxUtil.getDouble(goods, "SellPrice");//含税单价
                    price = VtuzxUtil.getDouble(goods, "ShareFavourableAfterFee");//含税单价
                    skuCount = VtuzxUtil.getInt(goods, "SellCount");
                }
                //查询单位编码
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",
                        "FNAME"
                ), cond);
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }
                //判断是否启用批号
                String floatCond = String.format("FNumber = '%s'", goodsNo);
                List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FIsBatchManage"
                ), floatCond);
                //获取单位编码
                boolean flag = true;
                if (bd_Material != null && bd_Material.size() > 0) {
                    flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                }
                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");//产品类型
                String flagForFSaledeptid = VtuzxUtil.getObject(FID, "flagForFSaledeptid");
                colMap.put("FSaledeptid", new VtuzxMap("FNumber", flagForFSaledeptid));//销售部门
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
                colMap.put("FRealQty", Math.abs(skuCount));//实退数量
                colMap.put("FTaxPrice", Math.abs(price / skuCount));//含税单价
                if (price == 0) {
                    colMap.put("FIsFree", true);//是否赠品
                } else {
                    colMap.put("FIsFree", false);//是否赠品
                }
                colMap.put("FBaseunitQty", Math.abs(skuCount));//库存基本数量
//                colMap.put("FEntryTaxRate", taxRate);//税率
                colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                String flagForFOwnerId = VtuzxUtil.getObject(FID, "flagForFOwnerId");
                colMap.put("FOwnerId", new Document("FNumber", flagForFOwnerId));//货主
                String flagForFOWNERID = VtuzxUtil.getObject(FID, "flagForFOWNERID");
                colMap.put("FOWNERID", new VtuzxMap("FNumber", flagForFOWNERID));//货主
                String flagForFOwnerID = VtuzxUtil.getObject(FID, "flagForFOwnerID");
                colMap.put("FOwnerID", new VtuzxMap("FNumber", flagForFOwnerID));//货主
                colMap.put("FStockID", new VtuzxMap("FNumber", flagForFStockID));//仓库
                colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                if (flag) {
                    colMap.put("FLot", new Document("FNumber", "88888"));//批号
                }
                colMap.put("FDeliveryDate", VtuzxUtil.formatYmdHmsF(new Date()));//退货日期
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSalUnitQty", Math.abs(skuCount));//销售数量
                colMap.put("FSalBaseQty", Math.abs(skuCount));//销售基本数量
                colMap.put("FPriceBaseQty", Math.abs(skuCount));//计价基本数量
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", Math.abs(skuCount));//未关联应收数量（计价单位
                colMap.put("FIsReturnCheck", false);//退货校验
                FEntity.add(colMap);
            }
        }
        //销售单情况
        if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "allocateNo"))) {//调拨单号为空
            String customerCode = VtuzxUtil.getString(data, "customerCode");//吉客云客户编号
            String shopName = VtuzxUtil.getString(data, "shopName");//销售渠道、店铺名称
            String JKYDH = VtuzxUtil.getString(data, "tradeNo");//吉客云销售单号
            double discountFee = VtuzxUtil.getDouble(data, "discountFee");//整单优惠
            String appendMemo = VtuzxUtil.getString(data, "appendMemo");//追加备注
            String sellerMemo = VtuzxUtil.getString(data, "sellerMemo");//客服备注
            double otherFee = VtuzxUtil.getDouble(data, "otherFee");//销售费用
            String onlineTradeNo = VtuzxUtil.getString(data, "onlineTradeNo");//网店单号
            String buyerMemo = VtuzxUtil.getString(data, "buyerMemo");//客户备注
            String flagNames = VtuzxUtil.getString(data, "flagNames");//标记
            double couponFee = VtuzxUtil.getDouble(data, "couponFee");//平台补贴
            String tradeTime = VtuzxUtil.getString(data, "tradeTime");//下单时间
            String createTime = VtuzxUtil.getString(data, "gmtCreate");//创建日期
            String flagForBillChannel = VtuzxUtil.getString(FID, "flagForBillChannel");//结算渠道
            saleModel.put("F_SXLJ_JKYKHBH", customerCode);//吉客云客户编号
            saleModel.put("F_PSUH_XSQD", shopName);//销售渠道
            saleModel.put("F_PSUH_XSDH", JKYDH);//吉客云销售单号
            saleModel.put("F_PSUH_JSDH", "--");//吉客云结算单号
            saleModel.put("F_ora_disFee", Math.abs(discountFee));//整单优惠
            if (VtuzxUtil.isEmpty(appendMemo)) {
                saleModel.put("F_ora_appendMemo", "--");//追加备注为空
            } else {
                saleModel.put("F_ora_appendMemo", appendMemo);//追加备注
            }
            if (VtuzxUtil.isEmpty(sellerMemo)) {
                saleModel.put("F_ora_kefuMemo", "--");//客服备注为空
            } else {
                saleModel.put("F_ora_kefuMemo", sellerMemo);//客服备注
            }
            saleModel.put("F_ora_saleFee", Math.abs(otherFee));//销售费用
            if (VtuzxUtil.isEmpty(onlineTradeNo)) {
                saleModel.put("F_ora_lineTradeNo", "--");//网店单号为空
            } else {
                saleModel.put("F_ora_lineTradeNo", onlineTradeNo);//网店单号
            }
            //saleModel.put("F_PSUH_KD",points);//扣点
            if (VtuzxUtil.isEmpty(buyerMemo)) {
                saleModel.put("F_ora_kehuMemo", "--");//客户备注为空
            } else {
                saleModel.put("F_ora_kehuMemo", buyerMemo);//客户备注
            }
            if (VtuzxUtil.isEmpty(flagNames)) {
                saleModel.put("F_PSUH_biaoji", "--");//标记为空
            } else {
                saleModel.put("F_PSUH_biaoji", flagNames);//标记
            }
            saleModel.put("F_PSUH_DPMC", shopName);//店铺名称
            saleModel.put("F_PSUH_couponFee", Math.abs(couponFee));//平台补贴
            saleModel.put("F_PSUH_XDSJ", tradeTime);//下单时间
            saleModel.put("F_PSUH_JSQD", new Document("FNumber", flagForBillChannel));//结算渠道
            //如果是寄存的单据,下单时间和创建时间在同月是正常销售单,不是同月的加一个寄存标记(为了不用算钱)
            if (flagNames.contains("寄存")) {
                if (!VtuzxUtil.isEmpty(tradeTime)) {
                    String createSub = createTime.substring(5, 7);//创建日期月份
                    String tradeSub = tradeTime.substring(5, 7);//下单日期月份
                    if (!createSub.equals(tradeSub)) {
                        saleModel.put("F_PSUH_JCBJ", "寄存");//寄存标记
                    }
                }
            } else {
                saleModel.put("F_PSUH_JCBJ", "--");//寄存标记为空
            }
            //调拨单情况
        } else if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "tradeNo"))) {//销售单号为空
            String JKYDH = VtuzxUtil.getString(data, "allocateNo");//吉客云调拨单号
            saleModel.put("F_PSUH_XSDH", "--");//吉客云销售单号
            saleModel.put("F_PSUH_JSDH", JKYDH);//吉客云结算单号
        }
        saleModel.put("SubHeadEntity", SubHeadEntity);
        saleModel.put("FEntity", FEntity);
        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", false);
        kneeParam.put("IsEntryBatchFill", true);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", saleModel);
        historyDoc.append("param", new VtuzxMap("SAL_RETURNSTOCK", kneeParam));
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", kneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
            historyDoc.append("syncTask", true);
        } catch (Exception e) {
            historyDoc.append("message", e.getMessage()).append("success", false);
        }
    }

    private void innerGetSaleData(Document storeDoc, String shopCode, VtuzxMap saleMap) throws Exception {
        VtuzxMap getSales = jiKeYunApiService.getSales(storeDoc,
                new VtuzxMap("code", shopCode)
                        .append("pageSize", 50)
                        .append("pageIndex", 0));
        Map<String, Object> result = VtuzxUtil.getObject(getSales, "result");
        Map<String, Object> data = VtuzxUtil.getObject(result, "data");
        List<Map<String, Object>> salesChannelInfo = VtuzxUtil.getObject(data, "salesChannelInfo");
        for (Map<String, Object> salesChannel : salesChannelInfo) {
            String companyName = VtuzxUtil.getString(salesChannel, "companyName");
            saleMap.append(shopCode, companyName);
        }
    }

    @Override
    public VtuzxMap getInnersettorderList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String billNo = VtuzxUtil.getString(param, "billNo");
        String orderNo = VtuzxUtil.getString(param, "orderNo");
        String sourceBillNo = VtuzxUtil.getString(param, "sourceBillNo");
        String inReldataName = VtuzxUtil.getString(param, "inReldataName");
        String outReldataName = VtuzxUtil.getString(param, "outReldataName");
        String outCompanyName = VtuzxUtil.getString(param, "outCompanyName");
        String inCompanyName = VtuzxUtil.getString(param, "inCompanyName");
        String isUpload = VtuzxUtil.getString(param, "isUpload");
        List<String> gmtCreate = VtuzxUtil.getObject(param, "gmtCreate");
        List<String> priceCheckedDate = VtuzxUtil.getObject(param, "priceCheckedDate");//核价日期
        List<String> settDate = VtuzxUtil.getObject(param, "settDate");//结算日期

        Criteria cond = new Criteria();
        cond.and("orderType").is(1);
        if (!VtuzxUtil.isEmpty(isUpload)) {
            cond.and("isUpload").is(isUpload);
        }
        if (!VtuzxUtil.isEmpty(billNo)) {
            cond.and("billNo").regex(billNo);
        }
        if (!VtuzxUtil.isEmpty(outReldataName)) {
            cond.and("outReldataName").regex(outReldataName);
        }
        if (!VtuzxUtil.isEmpty(outCompanyName)) {
            cond.and("outCompanyName").regex(outCompanyName);
        }
        if (!VtuzxUtil.isEmpty(inCompanyName)) {
            cond.and("inCompanyName").regex(inCompanyName);
        }
        if (!VtuzxUtil.isEmpty(inReldataName)) {
            cond.and("inReldataName").regex(inReldataName);
        }
        if (!VtuzxUtil.isEmpty(orderNo)) {
            cond.and("orderNo").regex(orderNo);
        }
        if (!VtuzxUtil.isEmpty(sourceBillNo)) {
            cond.and("sourceBillNo").regex(sourceBillNo);
        }
        if (!VtuzxUtil.isEmpty(gmtCreate)) {
            cond.and("gmtCreate").gte(VtuzxUtil.parseDate(gmtCreate.get(0)).getTime()).lte(VtuzxUtil.parseDate(gmtCreate.get(1) + " 23:59:59").getTime());
        }
        if (!VtuzxUtil.isEmpty(priceCheckedDate)) {
            cond.and("priceCheckedDate").gte(VtuzxUtil.parseDate(priceCheckedDate.get(0)).getTime()).lte(VtuzxUtil.parseDate(priceCheckedDate.get(1) + " 23:59:59").getTime());
        }
        if (!VtuzxUtil.isEmpty(settDate)) {
            cond.and("settDate").gte(VtuzxUtil.parseDate(settDate.get(0)).getTime()).lte(VtuzxUtil.parseDate(settDate.get(1) + " 23:59:59").getTime());
        }
        VtuzxPage page = innersettorderDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("orderType", VtuzxUtil.getInt(doc, "orderType"))//单据类型
                .append("billNo", VtuzxUtil.getString(doc, "billNo"))
                .append("orderNo", VtuzxUtil.getString(doc, "orderNo"))
                .append("outCompanyName", VtuzxUtil.getString(doc, "outCompanyName"))//应收公司
                .append("gmtCreate", VtuzxUtil.formatYmdHmsF(new Date(Long.parseLong(VtuzxUtil.getString(doc, "gmtCreate")))))
                .append("inCompanyName", VtuzxUtil.getString(doc, "inCompanyName"))//应付公司
                .append("settAmount", VtuzxUtil.getDouble(doc, "settAmount"))//结算金额
                .append("memo", VtuzxUtil.getString(doc, "memo"))//备注
                .append("outReldataName", VtuzxUtil.getString(doc, "outReldataName"))
                .append("sourceBillNo", VtuzxUtil.getString(doc, "sourceBillNo"))//对应销售单号
                .append("isUpload", VtuzxUtil.getString(doc, "isUpload"))
                .append("inReldataName", VtuzxUtil.getString(doc, "inReldataName"))//接收方
                .append("priceCheckedDate", VtuzxUtil.formatYmdHmsF(new Date(VtuzxUtil.getLong(doc, "priceCheckedDate"))))//核价日期
                .append("settDate", VtuzxUtil.formatYmdHmsF(new Date(VtuzxUtil.getLong(doc, "settDate"))))//结算日期
                .append("settUserName", VtuzxUtil.getString(doc, "settUserName")));

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public VtuzxMap getInnersettorderSaleList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String billNo = VtuzxUtil.getString(param, "billNo");
        String orderNo = VtuzxUtil.getString(param, "orderNo");
        String sourceBillNo = VtuzxUtil.getString(param, "sourceBillNo");
        String inReldataName = VtuzxUtil.getString(param, "inReldataName");
        String outReldataName = VtuzxUtil.getString(param, "outReldataName");
        String outCompanyName = VtuzxUtil.getString(param, "outCompanyName");
        String inCompanyName = VtuzxUtil.getString(param, "inCompanyName");
        String isUpload = VtuzxUtil.getString(param, "isUpload");
        List<String> gmtCreate = VtuzxUtil.getObject(param, "gmtCreate");
        List<String> priceCheckedDate = VtuzxUtil.getObject(param, "priceCheckedDate");//核价日期
        List<String> settDate = VtuzxUtil.getObject(param, "settDate");//结算日期

        Criteria cond = new Criteria();
        cond.and("orderType").is(2);
        if (!VtuzxUtil.isEmpty(isUpload)) {
            cond.and("isUpload").is(isUpload);
        }
        if (!VtuzxUtil.isEmpty(billNo)) {
            cond.and("billNo").regex(billNo);
        }
        if (!VtuzxUtil.isEmpty(outReldataName)) {
            cond.and("outReldataName").regex(outReldataName);
        }
        if (!VtuzxUtil.isEmpty(outCompanyName)) {
            cond.and("outCompanyName").regex(outCompanyName);
        }
        if (!VtuzxUtil.isEmpty(inCompanyName)) {
            cond.and("inCompanyName").regex(inCompanyName);
        }
        if (!VtuzxUtil.isEmpty(inReldataName)) {
            cond.and("inReldataName").regex(inReldataName);
        }
        if (!VtuzxUtil.isEmpty(orderNo)) {
            cond.and("orderNo").regex(orderNo);
        }
        if (!VtuzxUtil.isEmpty(sourceBillNo)) {
            cond.and("sourceBillNo").regex(sourceBillNo);
        }
        if (!VtuzxUtil.isEmpty(gmtCreate)) {
            cond.and("gmtCreate").gte(VtuzxUtil.parseDate(gmtCreate.get(0)).getTime()).lte(VtuzxUtil.parseDate(gmtCreate.get(1) + " 23:59:59").getTime());
        }
        if (!VtuzxUtil.isEmpty(priceCheckedDate)) {
            cond.and("priceCheckedDate").gte(VtuzxUtil.parseDate(priceCheckedDate.get(0)).getTime()).lte(VtuzxUtil.parseDate(priceCheckedDate.get(1) + " 23:59:59").getTime());
        }
        if (!VtuzxUtil.isEmpty(settDate)) {
            cond.and("settDate").gte(VtuzxUtil.parseDate(settDate.get(0)).getTime()).lte(VtuzxUtil.parseDate(settDate.get(1) + " 23:59:59").getTime());
        }
        VtuzxPage page = innersettorderDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("orderType", VtuzxUtil.getInt(doc, "orderType"))//单据类型
                .append("billNo", VtuzxUtil.getString(doc, "billNo"))
                .append("orderNo", VtuzxUtil.getString(doc, "orderNo"))
                .append("outCompanyName", VtuzxUtil.getString(doc, "outCompanyName"))//应收公司
                .append("gmtCreate", VtuzxUtil.formatYmdHmsF(new Date(Long.parseLong(VtuzxUtil.getString(doc, "gmtCreate")))))
                .append("inCompanyName", VtuzxUtil.getString(doc, "inCompanyName"))//应付公司
                .append("settAmount", VtuzxUtil.getDouble(doc, "settAmount"))//结算金额
                .append("memo", VtuzxUtil.getString(doc, "memo"))//备注
                .append("outReldataName", VtuzxUtil.getString(doc, "outReldataName"))
                .append("sourceBillNo", VtuzxUtil.getString(doc, "sourceBillNo"))//对应销售单号
                .append("isUpload", VtuzxUtil.getString(doc, "isUpload"))
                .append("inReldataName", VtuzxUtil.getString(doc, "inReldataName"))//接收方
                .append("priceCheckedDate", VtuzxUtil.formatYmdHmsF(new Date(VtuzxUtil.getLong(doc, "priceCheckedDate"))))//核价日期
                .append("settDate", VtuzxUtil.formatYmdHmsF(new Date(VtuzxUtil.getLong(doc, "settDate"))))//结算日期
                .append("settUserName", VtuzxUtil.getString(doc, "settUserName")));

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }


//    /**
//     * 传公司间结算单(销售类型)
//     * @param userId
//     * @param billNoList
//     * @return
//     * @throws Exception
//     */
//    @Override
//    public VtuzxMap uploadKingdeeInnersettorderSale(ObjectId userId,String userName, List<String> billNoList) throws Exception {
//        Iterator<Document> innersettorderItr = innersettorderDao.findList(Criteria.where("orderNo").in(billNoList), null, 0, 0);
//        List<Document> innersettorderList = new ArrayList<>();
//        while (innersettorderItr.hasNext()) {
//            Document innersettorderDoc = innersettorderItr.next();
//            innersettorderList.add(innersettorderDoc);
//        }
//        //金蝶token
////        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
//        //极客云token
//        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
//        //野象
//        VtuzxKingdeeCloudClient yxClient = kingdeeService.loginKingdeeYeXiang();
//        for (Document innerDoc : innersettorderList) {
//            String outCompanyName = VtuzxUtil.getString(innerDoc, "outCompanyName");//应收公司
//            String inCompanyName = VtuzxUtil.getString(innerDoc,"inCompanyName");//应付公司
//            String orderNo = VtuzxUtil.getString(innerDoc, "orderNo");
//            Document historyDoc = syncOrderDao.findOne(Criteria.where("billNo").is(orderNo));
//            ObjectId id = null;
//            if (historyDoc == null) {
//                historyDoc = new Document("billNo", orderNo);
//            } else {
//                id = VtuzxUtil.getObject(historyDoc, "_id");
//            }
//            historyDoc.append("billNo", orderNo);
//            historyDoc.append("userId", userId);
//            historyDoc.append("userName", "name");
//            historyDoc.append("source", "source");
//            historyDoc.append("data", innerDoc);
//            historyDoc.append("event", "innerSetter");
//
//            try {
//                if (outCompanyName.contains("晓芹") && inCompanyName.contains("野象")) {
//                    boolean isPositive = VtuzxUtil.getBoolean(innerDoc,"isPositive");
//                    if (!isPositive){//应收是晓芹，数量是负数的，野象传采购退，晓芹传销售退
//                        //判断是否已经上传
//                        String cond = String.format("F_PSUH_JSDH = '%s'", orderNo);
//                        List<VtuzxMap> saleOrder = kingdeeService.query(yxClient, "PUR_MRB", new VtuzxArrayList<>(
//                                "FBillNo"//单据编号
//                        ), cond);
//                        //说明已经传过,跳过当前循环
//                        if (saleOrder != null && saleOrder.size() > 0) {
//                            continue;
//                        }
//                        //先传调拨单，门店退货的调拨单
//                        syncKingdeeInnerAllocationReturn(yxClient,innerDoc,historyDoc,storeDoc);
//                        //传野象采购退
//                        syncKingdeeRefund(yxClient,innerDoc,historyDoc);
//                        //晓芹销售退
////                        syncKingdeeSaleRefund(client,innerDoc, historyDoc);
//                    } else {//应收是晓芹，数量是正数的，野象传采购入，晓芹销售出
//                        //判断是否已经上传
//                        String cond = String.format("F_PSUH_JSDH = '%s'", orderNo);
//                        List<VtuzxMap> saleOrder = kingdeeService.query(yxClient, "STK_InStock", new VtuzxArrayList<>(
//                                "FBillNo"//单据编号
//                        ), cond);
//                        //说明已经传过,跳过当前循环
//                        if (saleOrder != null && saleOrder.size() > 0) {
//                            continue;
//                        }
//                        //野象采购入
//                        syncKingdeeProcure(yxClient,innerDoc,historyDoc,storeDoc);
//                        //门店要货的传金蝶调拨单
//                        syncKingdeeInnerAllocation(yxClient,innerDoc,historyDoc,storeDoc);
//                        //晓芹传销售出
////                        int orderType = VtuzxUtil.getInt(innerDoc,"orderType");//单据类型
////                        if(orderType == 2){//销售类型
////                            suncKingdeeSaleOutOne(client,innerDoc,historyDoc);
////                        } else if (orderType == 1){//调拨类型
////                            syncKingdeeSaleAlocOne(client,innerDoc,historyDoc);
////                        }
//
//                    }
//                }
//                if (outCompanyName.contains("野象") && inCompanyName.contains("晓芹")) {//应收公司是野象
//                    boolean isPositive = VtuzxUtil.getBoolean(innerDoc,"isPositive");
//                    if(!isPositive){//应收是野象，数量是负数的，野象传销售退，晓芹传采购退
//                        //判断是否已经上传
//                        String cond = String.format("F_PSUH_JSDH = '%s'", orderNo);
//                        List<VtuzxMap> saleOrder = kingdeeService.query(yxClient, "SAL_RETURNSTOCK", new VtuzxArrayList<>(
//                                "FBillNo"//单据编号
//                        ), cond);
//                        //说明已经传过,跳过当前循环
//                        if (saleOrder != null && saleOrder.size() > 0) {
//                            continue;
//                        }
//
//                        //野象销售退
//                        syncKingdeeSaleRefundYX(yxClient,innerDoc,historyDoc);
//                        //晓芹采购退
////                        syncKingdeeRefundXY(client,innerDoc,historyDoc);
//                    } else {//应收是野象，数量是正数的，野象传销售出，晓芹传采购入
//                        //判断是否已经上传
//                        String cond = String.format("F_PSUH_JSDH = '%s'", orderNo);
//                        List<VtuzxMap> saleOrder = kingdeeService.query(yxClient, "SAL_OUTSTOCK", new VtuzxArrayList<>(
//                                "FBillNo"//单据编号
//                        ), cond);
//                        //说明已经传过,跳过当前循环
//                        if (saleOrder != null && saleOrder.size() > 0) {
//                            continue;
//                        }
//                        //野象销售出
//                        suncKingdeeSaleOutOneYX(yxClient,innerDoc,historyDoc);
//                        //晓芹采购入
////                        syncKingdeeProcureXQ(client,innerDoc,historyDoc);
//                    }
//
//                }
//                historyDoc.append("success", true);
//                if (id == null) {
//                    syncOrderDao.insertOne(historyDoc);
//                } else {
//                    historyDoc.remove("_id");
//                    historyDoc.remove("createTime");
//                    historyDoc.remove("updateTime");
//                    historyDoc.append("message","");
//                    historyDoc.append("updateUserId", userId);
//                    historyDoc.append("updateUserName", userName);
//                    syncOrderDao.updateById(id, historyDoc);
//                }
//                String _id = VtuzxUtil.getString(innerDoc, "_id");
//                innersettorderDao.updateById(_id, new Document("isUpload", "yes"));
//            } catch (Exception e){
//
//                historyDoc.append("prdInStockStock", false).append("message", e.getMessage()).append("success", false);
//
//                if (id == null) {
//                    syncOrderDao.insertOne(historyDoc);
//                } else {
//                    historyDoc.remove("_id");
//                    historyDoc.remove("createTime");
//                    historyDoc.remove("updateTime");
//                    syncOrderDao.updateById(id, historyDoc);
//                }
////                throw new VtuzxException(e.getMessage());
//                _logger.info(e.getMessage());
//            }
//
//        }
//        return new VtuzxMap();
//    }

    /**
     * 传公司间结算单
     *
     * @param userId
     * @param billNoList
     * @return
     * @throws Exception
     */
    @Override
    public VtuzxMap uploadKingdeeInnersettorder(ObjectId userId, String userName, List<String> billNoList, String orderTime) throws Exception {
        Iterator<Document> innersettorderItr = innersettorderDao.findList(Criteria.where("orderNo").in(billNoList), null, 0, 0);
        List<Document> innersettorderList = new ArrayList<>();
        while (innersettorderItr.hasNext()) {
            Document innersettorderDoc = innersettorderItr.next();
            innersettorderList.add(innersettorderDoc);
        }
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        //野象
        VtuzxKingdeeCloudClient yxClient = kingdeeService.loginKingdeeYeXiang();
        for (Document innerDoc : innersettorderList) {
            String outCompanyName = VtuzxUtil.getString(innerDoc, "outCompanyName");//应收公司
            String inCompanyName = VtuzxUtil.getString(innerDoc, "inCompanyName");//应付公司
            String outReldataName = VtuzxUtil.getString(innerDoc, "outReldataName");//供货方
            String inReldataName = VtuzxUtil.getString(innerDoc, "inReldataName");//接收方
            String orderNo = VtuzxUtil.getString(innerDoc, "orderNo");
            innerDoc.append("orderTime", orderTime);//前端选择的日期
            Document historyDoc = syncOrderDao.findOne(Criteria.where("billNo").is(orderNo));
            ObjectId id = null;
            if (historyDoc == null) {
                historyDoc = new Document("billNo", orderNo);
            } else {
                id = VtuzxUtil.getObject(historyDoc, "_id");
            }
            historyDoc.append("billNo", orderNo);
            historyDoc.append("userId", userId);
            historyDoc.append("userName", userName);
            historyDoc.append("source", "source");
            historyDoc.append("data", innerDoc);
            historyDoc.append("event", "innerSetter");

            try {
                //应收是大连晓芹，供货方是本埠物流仓的，接收方是野象仓库的属于门店要货
                if (outCompanyName.contains("大连晓芹")) {
                    if ("本埠物流仓".equals(outReldataName) && inReldataName.contains("百年晓芹") && inReldataName.startsWith("bb")) {
                        String cond = String.format("F_PSUH_JSDH = '%s'", orderNo);
                        List<VtuzxMap> saleOrder = kingdeeService.query(yxClient, "PUR_MRB", new VtuzxArrayList<>(
                                "FBillNo"//单据编号
                        ), cond);
                        //说明已经传过,跳过当前循环
                        if (saleOrder != null && saleOrder.size() > 0) {
                            continue;
                        }
                        //野象采购入
                        syncKingdeeProcure(yxClient, innerDoc, historyDoc, storeDoc);
                        //门店要货的传金蝶调拨单
                        syncKingdeeInnerAllocation(yxClient, innerDoc, historyDoc, storeDoc);
                    } else {
                        boolean isPositive = VtuzxUtil.getBoolean(innerDoc, "isPositive");
                        //判断数量是正还是负，负数的传采购退，正数的传采购入
                        if (!isPositive) {
                            //传野象采购退
                            syncKingdeeRefund(yxClient, innerDoc, historyDoc, orderTime);
                        } else {
                            //采购入
                            syncKingdeeProcure(yxClient, innerDoc, historyDoc, storeDoc);
                        }

                    }

                } else if (outCompanyName.contains("百年晓芹")) {//应收公司是野象，并且接收方是大连总售后退货仓的属于门店退货
                    if ("大连总售后退货仓".equals(inReldataName)) {

                        //判断是否已经上传
                        String cond = String.format("F_PSUH_JSDH = '%s'", orderNo);
                        List<VtuzxMap> saleOrder = kingdeeService.query(yxClient, "SAL_RETURNSTOCK", new VtuzxArrayList<>(
                                "FBillNo"//单据编号
                        ), cond);
                        //说明已经传过,跳过当前循环
                        if (saleOrder != null && saleOrder.size() > 0) {
                            continue;
                        }
                        //先传调拨单，门店退货的调拨单
                        syncKingdeeInnerAllocationReturn(yxClient, innerDoc, historyDoc, storeDoc);
                        //传野象采购退
                        syncKingdeeRefund(yxClient, innerDoc, historyDoc, orderTime);
                    } else {
                        //传野象采购退
                        syncKingdeeRefund(yxClient, innerDoc, historyDoc, orderTime);
                    }
                }
                historyDoc.append("success", true);
                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    historyDoc.append("message", "");
                    historyDoc.append("updateUserId", userId);
                    historyDoc.append("updateUserName", userName);
                    syncOrderDao.updateById(id, historyDoc);
                }
                String _id = VtuzxUtil.getString(innerDoc, "_id");
                innersettorderDao.updateById(_id, new Document("isUpload", "yes"));
            } catch (Exception e) {

                historyDoc.append("prdInStockStock", false).append("message", e.getMessage()).append("success", false);

                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    syncOrderDao.updateById(id, historyDoc);
                }
//                throw new VtuzxException(e.getMessage());
                _logger.info(e.getMessage());
            }

        }
        return new VtuzxMap();
    }

    /**
     * 直接调拨单(门店退货的)
     *
     * @param yxClient
     * @param innerDoc
     * @param historyDoc
     * @param storeDoc
     */
    private void syncKingdeeInnerAllocationReturn(VtuzxKingdeeCloudClient yxClient, Document innerDoc, Document historyDoc, Document storeDoc) throws Exception {
        String orderNo = VtuzxUtil.getString(innerDoc, "orderNo");
//        Long settDate = VtuzxUtil.getObject(innerDoc, "settDate");//创建时间
        String orderTime = VtuzxUtil.getString(innerDoc, "orderTime");//创建时间
        String outReldataName = VtuzxUtil.getString(innerDoc, "outReldataName");//供货方
        String suboutReldataName = outReldataName.substring(0, outReldataName.indexOf("-"));
        //查询渠道编号
        String qdNo = "";//渠道编码
        //查询客户
        String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", suboutReldataName, "A");
        List<VtuzxMap> bd_customer = kingdeeService.query(yxClient, "BD_Customer", new VtuzxArrayList<>(
                "FNumber",//客户编码
                "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                "FNAME"//客户名称
        ), cusCond);
        if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
            qdNo = VtuzxUtil.getString(bd_customer.get(0), "F_SXLJ_xsqd.FNUMBER");
        }

        String stockId = VtuzxUtil.getObject(innerDoc, "stockId");//金蝶仓库id
        Map<String, Object> param = new LinkedHashMap<>();
        Map<String, Object> model = new LinkedHashMap<>();
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID", new VtuzxMap("FNUMBER", "ZJDB01_SYS"));//单据类型
        model.put("FBizType", "NORMAL");//业务类型
        model.put("FTransferDirect", "GENERAL");//调拨方向(退货)
        model.put("FTransferBizType", "OverOrgTransfer");//调拨类型
        model.put("FSettleOrgId", new VtuzxMap("FNumber", "100"));//结算组织
        model.put("FSaleOrgId", new VtuzxMap("FNumber", "100"));//销售组织
        model.put("FStockOutOrgId", new VtuzxMap("FNumber", "100"));//调出库存组织
        model.put("FOwnerTypeOutIdHead", "BD_OwnerOrg");//调出货主类型
        model.put("FOwnerOutIdHead", new VtuzxMap("FNumber", "100"));//调出货主
        model.put("FStockOrgId", new VtuzxMap("FNumber", "200"));//调入库存组织
        model.put("FIsIncludedTax", true);//是否含税
        model.put("FIsPriceExcludeTax", true);//价外税
        model.put("FExchangeTypeId", new VtuzxMap("FNUMBER", "HLTX01_SYS"));//汇率类型
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//调入货主类型
        model.put("FSETTLECURRID", new VtuzxMap("FNumber", "PRE001"));
        model.put("FExchangeRate", 1.0);
        model.put("FOwnerIdHead", new VtuzxMap("FNumber", "200"));
//        model.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));
        model.put("FDate", orderTime);
        model.put("FBaseCurrId", new VtuzxMap("FNumber", "PRE001"));
        model.put("FWriteOffConsign", false);//冲减普通寄售调拔单结算数量
        List<Map<String, Object>> FInStockEntry = new ArrayList<>();//单据体体数据

        //根据结算单号查询货品信息
        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合

        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
            Document getGoods = (Document) goodsMap.get(goodsNo);
            if (!materialNoList.contains(goodsNo)) {
                materialNoList.add(goodsNo);
            }
            if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                goodsMap.put(goodsNo, doc);
            } else {
                int skuCount = VtuzxUtil.getInt(doc, "skuCount");
                int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                doc.replace("skuCount", skuCount + skuNowCount);
                goodsMap.put(goodsNo, doc);
            }
        }
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称

            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }

        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");

            priceMap.put(materialNo, currentPrice);
        }
        //循环货品集合，添加金蝶单据体信息
        for (Map.Entry entry : goodsMap.entrySet()) {
            Document doc = (Document) entry.getValue();
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");//货品编号
//            double settPrice = VtuzxUtil.getDouble(doc, "settPrice");//结算金额
            double settPrice = (double) priceMap.get(goodsNo);
            String unitName = VtuzxUtil.getString(doc, "unitName");
            double skuCount = VtuzxUtil.getDouble(doc, "skuCount");
            //查询单位编码，直接传文字无效
            String unit = (String) unitMap.get(unitName);
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new VtuzxMap("FNumber", goodsNo));
            colMap.put("FUnitID", new VtuzxMap("FNumber", unit));
            colMap.put("FQty", skuCount);
            colMap.put("FSrcStockId", new VtuzxMap("FNumber", stockId));//调出仓库(门店仓库)
            colMap.put("FDestStockId", new VtuzxMap("FNumber", "001"));//调入仓库
            colMap.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调出库存装填
            colMap.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调入库存状态
//            colMap.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
//            colMap.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            colMap.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
            colMap.put("FOwnerTypeOutId", "BD_OwnerOrg");
            colMap.put("FOwnerOutId", new VtuzxMap("FNumber", "100"));
            colMap.put("FOwnerTypeId", "BD_OwnerOrg");
            colMap.put("FOwnerId", new VtuzxMap("FNumber", "200"));
            colMap.put("FSecQty", 0);
            colMap.put("FExtAuxUnitQty", 0);
            colMap.put("FBaseUnitId", new VtuzxMap("FNumber", unit));
            colMap.put("FBaseQty", skuCount);
            colMap.put("FISFREE", false);
            colMap.put("FKeeperTypeId", "BD_KeeperOrg");
            colMap.put("FActQty", 0);
            colMap.put("FKeeperId", new VtuzxMap("FNumber", "200"));
            colMap.put("FKeeperTypeOutId", "BD_KeeperOrg");
            colMap.put("FKeeperOutId", new VtuzxMap("FNumber", "100"));
            colMap.put("FDiscountRate", 0);
            colMap.put("FRepairQty", 0);
            colMap.put("FDestMaterialId", new VtuzxMap("FNumber", goodsNo));
            colMap.put("FSaleUnitId", new VtuzxMap("FNumber", unit));
            colMap.put("FSaleQty", skuCount);

            colMap.put("FSalBaseQty", skuCount);
            colMap.put("FPriceUnitID", new VtuzxMap("FNumber", unit));
            colMap.put("FPriceQty", skuCount);
            colMap.put("FPriceBaseQty", skuCount);
            colMap.put("FOutJoinQty", 0);
            colMap.put("FBASEOUTJOINQTY", 0);
            colMap.put("FSOEntryId", 0);

            colMap.put("FTransReserveLink", false);
            colMap.put("FQmEntryId", 0);
            colMap.put("FConvertEntryId", 0);
            colMap.put("FCheckDelivery", false);
            colMap.put("FBomEntryId", false);
            colMap.put("F_PSUH_QD", new Document("FNumber", qdNo));
            FInStockEntry.add(colMap);
        }


        model.put("FBillEntry", FInStockEntry);
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("IsAutoAdjustField", false);
        param.put("InterationFlags", "");
        param.put("IgnoreInterationFlag", "");
        param.put("IsControlPrecision", false);
        param.put("ValidateRepeatJson", false);
        param.put("Model", model);
        try {
            List<VtuzxMap> transferList = kingdeeService.save(yxClient, "STK_TransferDirect", param);
            VtuzxMap transferMap = transferList.get(0);
            String number = VtuzxUtil.getString(transferMap, "Number");
            kingdeeService.submit(yxClient, "STK_TransferDirect", "0", number);
            kingdeeService.audit(yxClient, "STK_TransferDirect", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            _logger.info(e.getMessage());
        }

    }

    /**
     * 直接调拨单(门店退货的)Task
     *
     * @param client
     * @param goodsList
     * @param historyDoc
     * @param FID
     */
    private void syncKingdeeInnerAllocationReturnTask(VtuzxKingdeeCloudClient client, List<Document> goodsList, Document historyDoc, VtuzxMap FID) throws Exception {
        Map<String, Object> param = new LinkedHashMap<>();
        Map<String, Object> model = new LinkedHashMap<>();
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID", new VtuzxMap("FNUMBER", "ZJDB01_SYS"));//单据类型
        model.put("FBizType", "NORMAL");//业务类型
        model.put("FTransferDirect", "GENERAL");//调拨方向(退货)
        model.put("FTransferBizType", "OverOrgTransfer");//调拨类型
        model.put("FSettleOrgId", new VtuzxMap("FNumber", "100"));//结算组织
        model.put("FSaleOrgId", new VtuzxMap("FNumber", "100"));//销售组织
        model.put("FStockOutOrgId", new VtuzxMap("FNumber", "100"));//调出库存组织
        model.put("FOwnerTypeOutIdHead", "BD_OwnerOrg");//调出货主类型
        model.put("FOwnerOutIdHead", new VtuzxMap("FNumber", "100"));//调出货主
        model.put("FStockOrgId", new VtuzxMap("FNumber", "200"));//调入库存组织
        model.put("FIsIncludedTax", true);//是否含税
        model.put("FIsPriceExcludeTax", true);//价外税
        model.put("FExchangeTypeId", new VtuzxMap("FNUMBER", "HLTX01_SYS"));//汇率类型
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//调入货主类型
        model.put("FSETTLECURRID", new VtuzxMap("FNumber", "PRE001"));
        model.put("FExchangeRate", 1.0);
        model.put("FOwnerIdHead", new VtuzxMap("FNumber", "200"));
        model.put("FBaseCurrId", new VtuzxMap("FNumber", "PRE001"));
        model.put("FWriteOffConsign", false);//冲减普通寄售调拔单结算数量
        List<Map<String, Object>> FInStockEntry = new ArrayList<>();//单据体体数据
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
            Document getGoods = (Document) goodsMap.get(goodsNo);
            if (!materialNoList.contains(goodsNo)) {
                materialNoList.add(goodsNo);
            }
            if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                goodsMap.put(goodsNo, doc);
            } else {
                int skuCount = VtuzxUtil.getInt(doc, "skuCount");
                int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                doc.replace("skuCount", skuCount + skuNowCount);
                goodsMap.put(goodsNo, doc);
            }
        }
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");
            priceMap.put(materialNo, currentPrice);
        }
        //循环货品集合，添加金蝶单据体信息
        for (Map.Entry entry : goodsMap.entrySet()) {
            Document doc = (Document) entry.getValue();
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");//货品编号
            double settPrice = (double) priceMap.get(goodsNo);
            String unitName = VtuzxUtil.getString(doc, "unitName");
            double skuCount = VtuzxUtil.getDouble(doc, "skuCount");
            //查询单位编码，直接传文字无效
            String unit = (String) unitMap.get(unitName);
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new VtuzxMap("FNumber", goodsNo));
            colMap.put("FUnitID", new VtuzxMap("FNumber", unit));
            colMap.put("FQty", skuCount);
            String flagForFSrcStockID = VtuzxUtil.getString(FID, "flagForFSrcStockID");
            colMap.put("FSrcStockId", new Document("FNumber", flagForFSrcStockID));//调出仓库
            String flagForFDestStockId = VtuzxUtil.getString(FID, "flagForFDestStockId");
            colMap.put("FDestStockId", new Document("FNumber", flagForFDestStockId));//调入仓库
            colMap.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调出库存装填
            colMap.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调入库存状态
            colMap.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
            colMap.put("FOwnerTypeOutId", "BD_OwnerOrg");
            colMap.put("FOwnerOutId", new VtuzxMap("FNumber", "100"));
            colMap.put("FOwnerTypeId", "BD_OwnerOrg");
            colMap.put("FOwnerId", new VtuzxMap("FNumber", "200"));
            colMap.put("FSecQty", 0);
            colMap.put("FExtAuxUnitQty", 0);
            colMap.put("FBaseUnitId", new VtuzxMap("FNumber", unit));
            colMap.put("FBaseQty", skuCount);
            colMap.put("FISFREE", false);
            colMap.put("FKeeperTypeId", "BD_KeeperOrg");
            colMap.put("FActQty", 0);
            colMap.put("FKeeperId", new VtuzxMap("FNumber", "200"));
            colMap.put("FKeeperTypeOutId", "BD_KeeperOrg");
            colMap.put("FKeeperOutId", new VtuzxMap("FNumber", "100"));
            colMap.put("FDiscountRate", 0);
            colMap.put("FRepairQty", 0);
            colMap.put("FDestMaterialId", new VtuzxMap("FNumber", goodsNo));
            colMap.put("FSaleUnitId", new VtuzxMap("FNumber", unit));
            colMap.put("FSaleQty", skuCount);
            colMap.put("FSalBaseQty", skuCount);
            colMap.put("FPriceUnitID", new VtuzxMap("FNumber", unit));
            colMap.put("FPriceQty", skuCount);
            colMap.put("FPriceBaseQty", skuCount);
            colMap.put("FOutJoinQty", 0);
            colMap.put("FBASEOUTJOINQTY", 0);
            colMap.put("FSOEntryId", 0);
            colMap.put("FTransReserveLink", false);
            colMap.put("FQmEntryId", 0);
            colMap.put("FConvertEntryId", 0);
            colMap.put("FCheckDelivery", false);
            colMap.put("FBomEntryId", false);
            FInStockEntry.add(colMap);
        }
        model.put("FBillEntry", FInStockEntry);
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("IsAutoAdjustField", false);
        param.put("InterationFlags", "");
        param.put("IgnoreInterationFlag", "");
        param.put("IsControlPrecision", false);
        param.put("ValidateRepeatJson", false);
        param.put("Model", model);
        try {
            List<VtuzxMap> transferList = kingdeeService.save(client, "STK_TransferDirect", param);
            VtuzxMap transferMap = transferList.get(0);
            String number = VtuzxUtil.getString(transferMap, "Number");
            kingdeeService.submit(client, "STK_TransferDirect", "0", number);
            kingdeeService.audit(client, "STK_TransferDirect", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            historyDoc.append("message", e.getMessage()).append("success", false);
        }
    }

    /**
     * 门店要货的传金蝶调拨单
     *
     * @param yxClient
     * @param innerDoc
     * @param historyDoc
     * @param storeDoc
     * @throws Exception
     */
    private void syncKingdeeInnerAllocation(VtuzxKingdeeCloudClient yxClient, Document innerDoc, Document historyDoc, Document storeDoc) throws Exception {
        String orderNo = VtuzxUtil.getString(innerDoc, "orderNo");
        Long settDate = VtuzxUtil.getObject(innerDoc, "settDate");//创建时间
        String inReldataName = VtuzxUtil.getString(innerDoc, "inReldataName");//接收方
        String subinReldataName = inReldataName.substring(0, inReldataName.indexOf("-"));
        //查询渠道编号
        String qdNo = "";//渠道编码
        //查询客户
        String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", subinReldataName, "A");
        List<VtuzxMap> bd_customer = kingdeeService.query(yxClient, "BD_Customer", new VtuzxArrayList<>(
                "FNumber",//客户编码
                "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                "FNAME"//客户名称
        ), cusCond);
        if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
            qdNo = VtuzxUtil.getString(bd_customer.get(0), "F_SXLJ_xsqd.FNUMBER");
        }

        String stockId = VtuzxUtil.getObject(innerDoc, "stockId");//金蝶仓库id
        Map<String, Object> param = new LinkedHashMap<>();
        Map<String, Object> model = new LinkedHashMap<>();
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID", new VtuzxMap("FNUMBER", "ZJDB01_SYS"));//单据类型
        model.put("FBizType", "NORMAL");//业务类型
        model.put("FTransferDirect", "GENERAL");//调拨方向
        model.put("FTransferBizType", "OverOrgTransfer");//调拨类型
        model.put("FSettleOrgId", new VtuzxMap("FNumber", "200"));//结算组织
        model.put("FSaleOrgId", new VtuzxMap("FNumber", "200"));//销售组织
        model.put("FStockOutOrgId", new VtuzxMap("FNumber", "200"));//调出库存组织
        model.put("FOwnerTypeOutIdHead", "BD_OwnerOrg");//调出货主类型
        model.put("FOwnerOutIdHead", new VtuzxMap("FNumber", "200"));//调出货主
        model.put("FStockOrgId", new VtuzxMap("FNumber", "100"));//调入库存组织
        model.put("FIsIncludedTax", true);//是否含税
        model.put("FIsPriceExcludeTax", true);//价外税
        model.put("FExchangeTypeId", new VtuzxMap("FNUMBER", "HLTX01_SYS"));//汇率类型
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//调入货主类型
        model.put("FSETTLECURRID", new VtuzxMap("FNumber", "PRE001"));
        model.put("FExchangeRate", 1.0);
        model.put("FOwnerIdHead", new VtuzxMap("FNumber", "100"));
        model.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));
        model.put("FBaseCurrId", new VtuzxMap("FNumber", "PRE001"));
        model.put("FWriteOffConsign", false);//冲减普通寄售调拔单结算数量
        List<Map<String, Object>> FInStockEntry = new ArrayList<>();//单据体体数据

        //根据结算单号查询货品信息
        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合

        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
            Document getGoods = (Document) goodsMap.get(goodsNo);
            if (!materialNoList.contains(goodsNo)) {
                materialNoList.add(goodsNo);
            }
            if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                goodsMap.put(goodsNo, doc);
            } else {
                int skuCount = VtuzxUtil.getInt(doc, "skuCount");
                int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                doc.replace("skuCount", skuCount + skuNowCount);
                goodsMap.put(goodsNo, doc);
            }
        }
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称

            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }

        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");

            priceMap.put(materialNo, currentPrice);
        }
        //循环货品集合，添加金蝶单据体信息
        for (Map.Entry entry : goodsMap.entrySet()) {
            Document doc = (Document) entry.getValue();
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");//货品编号
//            double settPrice = VtuzxUtil.getDouble(doc, "settPrice");//结算金额
            double settPrice = (double) priceMap.get(goodsNo);
            String unitName = VtuzxUtil.getString(doc, "unitName");
            double skuCount = VtuzxUtil.getDouble(doc, "skuCount");
            //查询单位编码，直接传文字无效
            String unit = (String) unitMap.get(unitName);
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new VtuzxMap("FNumber", goodsNo));
            colMap.put("FUnitID", new VtuzxMap("FNumber", unit));
            colMap.put("FQty", skuCount);
            colMap.put("FSrcStockId", new VtuzxMap("FNumber", "001"));//调出仓库
            colMap.put("FDestStockId", new VtuzxMap("FNumber", stockId));//调入仓库
            colMap.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调出库存装填
            colMap.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调入库存状态
//            colMap.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
//            colMap.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            colMap.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
            colMap.put("FOwnerTypeOutId", "BD_OwnerOrg");
            colMap.put("FOwnerOutId", new VtuzxMap("FNumber", "200"));
            colMap.put("FOwnerTypeId", "BD_OwnerOrg");
            colMap.put("FOwnerId", new VtuzxMap("FNumber", "100"));
            colMap.put("FBaseUnitId", new VtuzxMap("FNumber", unit));
            colMap.put("FBaseQty", skuCount);
            colMap.put("FISFREE", false);
            colMap.put("FKeeperTypeId", "BD_KeeperOrg");
            colMap.put("FKeeperId", new VtuzxMap("FNumber", "100"));
            colMap.put("FKeeperTypeOutId", "BD_KeeperOrg");
            colMap.put("FKeeperOutId", new VtuzxMap("FNumber", "200"));
            colMap.put("FDestMaterialId", new VtuzxMap("FNumber", goodsNo));
            colMap.put("FSaleUnitId", new VtuzxMap("FNumber", unit));
            colMap.put("FSaleQty", skuCount);
            colMap.put("FSalBaseQty", skuCount);
            colMap.put("FPriceUnitID", new VtuzxMap("FNumber", unit));
            colMap.put("FPriceQty", skuCount);
            colMap.put("FPriceBaseQty", skuCount);
            colMap.put("FTransReserveLink", false);
            colMap.put("FCheckDelivery", false);
            colMap.put("F_PSUH_QD", new Document("FNumber", qdNo));
            FInStockEntry.add(colMap);
        }


        model.put("FBillEntry", FInStockEntry);
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("IsAutoAdjustField", false);
        param.put("InterationFlags", "");
        param.put("IgnoreInterationFlag", "");
        param.put("IsControlPrecision", false);
        param.put("ValidateRepeatJson", false);
        param.put("Model", model);
        try {
            List<VtuzxMap> transferList = kingdeeService.save(yxClient, "STK_TransferDirect", param);
            VtuzxMap transferMap = transferList.get(0);
            String number = VtuzxUtil.getString(transferMap, "Number");
            kingdeeService.submit(yxClient, "STK_TransferDirect", "0", number);
            kingdeeService.audit(yxClient, "STK_TransferDirect", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            _logger.info(e.getMessage());
        }
    }

    /**
     * 直接调拨单Task
     *
     * @param client
     * @param goodsList
     * @param historyDoc
     * @param FID
     * @throws Exception
     */
    private void syncKingdeeInnerAllocationTask(VtuzxKingdeeCloudClient client, Document data, List<Document> goodsList, Document historyDoc, VtuzxMap FID) throws Exception {
        Map<String, Object> param = new LinkedHashMap<>();
        Map<String, Object> model = new LinkedHashMap<>();
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID", new VtuzxMap("FNUMBER", "ZJDB01_SYS"));//单据类型
        model.put("FBizType", "NORMAL");//业务类型
        model.put("FTransferDirect", "GENERAL");//调拨方向
        if(!VtuzxUtil.isEmpty(VtuzxUtil.getString(FID, "flagForFTransferBizType"))){
            model.put("FTransferBizType", VtuzxUtil.getString(FID, "flagForFTransferBizType"));//调拨类型
        } else {
            model.put("FTransferBizType", "OverOrgTransfer");//调拨类型
        }
        String JKYNo;
        if(VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "tradeNo"))){
            JKYNo = VtuzxUtil.getString(data, "allocateNo");//调拨单号
        }else {
            JKYNo = VtuzxUtil.getString(data, "tradeNo");//销售单号
        }
        model.put("F_PSUH_JKY ", JKYNo);//备注(吉客云单号)
        String flagForFSettleOrgId = VtuzxUtil.getString(FID, "flagForFSettleOrgId");
        model.put("FSettleOrgId", new Document("FNumber", flagForFSettleOrgId));//结算组织
        String flagForFSaleOrgId = VtuzxUtil.getString(FID, "flagForFSaleOrgId");
        model.put("FSaleOrgId", new Document("FNumber", flagForFSaleOrgId));//销售组织
        String flagForFStockOutOrgId = VtuzxUtil.getString(FID, "flagForFStockOutOrgId");
        model.put("FStockOutOrgId", new Document("FNumber", flagForFStockOutOrgId));//调出库存组织
        model.put("FOwnerTypeOutIdHead", "BD_OwnerOrg");//调出货主类型
        String flagForFOwnerOutIdHead = VtuzxUtil.getString(FID, "flagForFOwnerOutIdHead");
        model.put("FOwnerOutIdHead", new Document("FNumber", flagForFOwnerOutIdHead));//调出货主
        String flagForFStockOrgId = VtuzxUtil.getString(FID, "flagForFStockOrgId");
        model.put("FStockOrgId", new Document("FNumber", flagForFStockOrgId));//调入库存组织
        String flagForFOUTDEPTID = VtuzxUtil.getString(FID, "flagForFOUTDEPTID");
        model.put("FOUTDEPTID", new Document("FNumber", flagForFOUTDEPTID));//调出部门
        String flagForFINDEPTID = VtuzxUtil.getString(FID, "flagForFINDEPTID");
        model.put("FINDEPTID", new Document("FNumber", flagForFINDEPTID));//调入部门
        model.put("FIsIncludedTax", true);//是否含税
        model.put("FIsPriceExcludeTax", true);//价外税
        model.put("FExchangeTypeId", new VtuzxMap("FNUMBER", "HLTX01_SYS"));//汇率类型
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//调入货主类型
        model.put("FSETTLECURRID", new VtuzxMap("FNumber", "PRE001"));
        model.put("FExchangeRate", 1.0);
        String flagForFOwnerIdHead = VtuzxUtil.getString(FID, "flagForFOwnerIdHead");
        model.put("FOwnerIdHead", new Document("FNumber", flagForFOwnerIdHead));
        model.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));
        model.put("FBaseCurrId", new VtuzxMap("FNumber", "PRE001"));
        model.put("FWriteOffConsign", false);//冲减普通寄售调拔单结算数量
        List<Map<String, Object>> FInStockEntry = new ArrayList<>();//单据体体数据
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> fitOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(fitOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(fitOrder, "goodsNo");
                        Document getGoods = (Document) goodsMap.get(goodsNo);
                        if (!materialNoList.contains(goodsNo)) {
                            materialNoList.add(goodsNo);
                        }
                        if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                            goodsMap.put(goodsNo, fitOrder);
                        } else {
                            int skuCount = VtuzxUtil.getInt(fitOrder, "skuCount");
                            int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                            fitOrder.replace("skuCount", skuCount + skuNowCount);
                            goodsMap.put(goodsNo, fitOrder);
                        }
                    }
                    /*Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
                    Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
                    //查询物料表获取税率信息
                    Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
                    while (materials.hasNext()) {
                        Document materialDoc = materials.next();
                        String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
                        String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
                        String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
                        String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
                        String substring = "";
                        if (fTaxRateName.startsWith("零")) {
                            substring = "0";
                        } else {
                            substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
                        }
                        taxMap.put(materialNo, Double.parseDouble(substring));
                        unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
                    }
                    //查询价目表获取价格信息
                    Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
                    Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
                    while (priceItr.hasNext()) {
                        Document priceDoc = priceItr.next();
                        String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
                        Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");
                        priceMap.put(materialNo, currentPrice);
                    }*/
                    /*//循环货品集合，添加金蝶单据体信息
                    for (Map.Entry entry : goodsMap.entrySet()) {
                        Document goodsDoc = (Document) entry.getValue();
                        String goodsNo = VtuzxUtil.getString(goodsDoc, "goodsNo");//货品编号
                        double price = (double) priceMap.get(goodsNo);
                        String unitName = VtuzxUtil.getString(goodsDoc, "unitName");
                        double skuCount = VtuzxUtil.getDouble(goodsDoc, "skuCount");
                        //查询单位编码，直接传文字无效
                        String unit = (String) unitMap.get(unitName);
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");//产品类型
                        colMap.put("FMaterialId", new VtuzxMap("FNumber", goodsNo));
                        colMap.put("FUnitID", new VtuzxMap("FNumber", unit));
                        colMap.put("FQty", skuCount);
                        String flagForFSrcStockID = VtuzxUtil.getString(FID, "flagForFSrcStockID");
                        colMap.put("FSrcStockId", new Document("FNumber", flagForFSrcStockID));//调出仓库
                        String flagForFDestStockId = VtuzxUtil.getString(FID, "flagForFDestStockId");
                        colMap.put("FDestStockId", new Document("FNumber", flagForFDestStockId));//调入仓库
                        colMap.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调出库存装填
                        colMap.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调入库存状态
                        colMap.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
                        colMap.put("FOwnerTypeOutId", "BD_OwnerOrg");
                        String flagForFOwnerOutId = VtuzxUtil.getString(FID, "flagForFOwnerOutId");
                        colMap.put("FOwnerOutId", new Document("FNumber", flagForFOwnerOutId));
                        colMap.put("FOwnerTypeId", "BD_OwnerOrg");
                        colMap.put("FTaxPrice", price);
                        String flagForFOwnerId = VtuzxUtil.getString(FID, "flagForFOwnerId");
                        colMap.put("FOwnerId", new Document("FNumber", flagForFOwnerId));
                        colMap.put("FBaseUnitId", new VtuzxMap("FNumber", unit));
                        colMap.put("FBaseQty", skuCount);
                        colMap.put("FISFREE", false);
                        colMap.put("FKeeperTypeId", "BD_KeeperOrg");
                        String flagForFKeeperId = VtuzxUtil.getString(FID, "flagForFKeeperId");
                        colMap.put("FKeeperId", new Document("FNumber", flagForFKeeperId));
                        colMap.put("FKeeperTypeOutId", "BD_KeeperOrg");
                        String flagForFKeeperOutId = VtuzxUtil.getString(FID, "flagForFKeeperOutId");
                        colMap.put("FKeeperOutId", new Document("FNumber", flagForFKeeperOutId));
                        colMap.put("FDestMaterialId", new VtuzxMap("FNumber", goodsNo));
                        colMap.put("FSaleUnitId", new VtuzxMap("FNumber", unit));
                        colMap.put("FSaleQty", skuCount);
                        colMap.put("FSalBaseQty", skuCount);
                        colMap.put("FPriceUnitID", new VtuzxMap("FNumber", unit));
                        colMap.put("FPriceQty", skuCount);
                        colMap.put("FPriceBaseQty", skuCount);
                        colMap.put("FTransReserveLink", false);
                        colMap.put("FCheckDelivery", false);
                        FInStockEntry.add(colMap);
                    }*/
                }
            } else {
                Document noFitDoc = new Document(goods);
                String goodsNo = VtuzxUtil.getString(noFitDoc, "goodsNo");
                Document getGoods = (Document) goodsMap.get(goodsNo);
                if (!materialNoList.contains(goodsNo)) {
                    materialNoList.add(goodsNo);
                }
                if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                    goodsMap.put(goodsNo, noFitDoc);
                } else {
                    int skuCount = VtuzxUtil.getInt(noFitDoc, "skuCount");
                    int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                    noFitDoc.replace("skuCount", skuCount + skuNowCount);
                    goodsMap.put(goodsNo, noFitDoc);
                }
                /*Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
                Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
                //查询物料表获取税率信息
                Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
                while (materials.hasNext()) {
                    Document materialDoc = materials.next();
                    String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
                    String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
                    String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
                    String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
                    String substring = "";
                    if (fTaxRateName.startsWith("零")) {
                        substring = "0";
                    } else {
                        substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
                    }
                    taxMap.put(materialNo, Double.parseDouble(substring));
                    unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
                }
                //查询价目表获取价格信息
                Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
                Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
                while (priceItr.hasNext()) {
                    Document priceDoc = priceItr.next();
                    String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
                    Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");
                    priceMap.put(materialNo, currentPrice);
                }*/
                /*//循环货品集合，添加金蝶单据体信息
                for (Map.Entry entry : goodsMap.entrySet()) {
                    Document goodsDoc = (Document) entry.getValue();
                    String nofitGoodsNo = VtuzxUtil.getString(goodsDoc, "goodsNo");//货品编号
                    double price = (double) priceMap.get(nofitGoodsNo);
                    String unitName = VtuzxUtil.getString(goodsDoc, "unitName");
                    double skuCount = VtuzxUtil.getDouble(goodsDoc, "skuCount");
                    //查询单位编码，直接传文字无效
                    String unit = (String) unitMap.get(unitName);
                    Map<String, Object> colMap = new LinkedHashMap<>();
                    colMap.put("FRowType", "Standard");//产品类型
                    colMap.put("FMaterialId", new VtuzxMap("FNumber", nofitGoodsNo));
                    colMap.put("FUnitID", new VtuzxMap("FNumber", unit));
                    colMap.put("FQty", skuCount);
                    String flagForFSrcStockID = VtuzxUtil.getString(FID, "flagForFSrcStockID");
                    colMap.put("FSrcStockId", new Document("FNumber", flagForFSrcStockID));//调出仓库
                    String flagForFDestStockId = VtuzxUtil.getString(FID, "flagForFDestStockId");
                    colMap.put("FDestStockId", new Document("FNumber", flagForFDestStockId));//调入仓库
                    colMap.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调出库存装填
                    colMap.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调入库存状态
                    colMap.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
                    colMap.put("FOwnerTypeOutId", "BD_OwnerOrg");
                    String flagForFOwnerOutId = VtuzxUtil.getString(FID, "flagForFOwnerOutId");
                    colMap.put("FOwnerOutId", new Document("FNumber", flagForFOwnerOutId));
                    colMap.put("FOwnerTypeId", "BD_OwnerOrg");
                    colMap.put("FTaxPrice", price);
                    String flagForFOwnerId = VtuzxUtil.getString(FID, "flagForFOwnerId");
                    colMap.put("FOwnerId", new Document("FNumber", flagForFOwnerId));
                    colMap.put("FBaseUnitId", new VtuzxMap("FNumber", unit));
                    colMap.put("FBaseQty", skuCount);
                    colMap.put("FISFREE", false);
                    colMap.put("FKeeperTypeId", "BD_KeeperOrg");
                    String flagForFKeeperId = VtuzxUtil.getString(FID, "flagForFKeeperId");
                    colMap.put("FKeeperId", new Document("FNumber", flagForFKeeperId));
                    colMap.put("FKeeperTypeOutId", "BD_KeeperOrg");
                    String flagForFKeeperOutId = VtuzxUtil.getString(FID, "flagForFKeeperOutId");
                    colMap.put("FKeeperOutId", new Document("FNumber", flagForFKeeperOutId));
                    colMap.put("FDestMaterialId", new VtuzxMap("FNumber", nofitGoodsNo));
                    colMap.put("FSaleUnitId", new VtuzxMap("FNumber", unit));
                    colMap.put("FSaleQty", skuCount);
                    colMap.put("FSalBaseQty", skuCount);
                    colMap.put("FPriceUnitID", new VtuzxMap("FNumber", unit));
                    colMap.put("FPriceQty", skuCount);
                    colMap.put("FPriceBaseQty", skuCount);
                    colMap.put("FTransReserveLink", false);
                    colMap.put("FCheckDelivery", false);
                    FInStockEntry.add(colMap);
                }*/
            }
        }
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");
            priceMap.put(materialNo, currentPrice);
        }
        //循环货品集合，添加金蝶单据体信息
        for (Map.Entry entry : goodsMap.entrySet()) {
            Document goodsDoc = (Document) entry.getValue();
            String nofitGoodsNo = VtuzxUtil.getString(goodsDoc, "goodsNo");//货品编号
            double price = (double) priceMap.get(nofitGoodsNo);
            String unitName = VtuzxUtil.getString(goodsDoc, "unitName");
            double skuCount = VtuzxUtil.getDouble(goodsDoc, "skuCount");
            //查询单位编码，直接传文字无效
            String unit = (String) unitMap.get(unitName);
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new VtuzxMap("FNumber", nofitGoodsNo));
            colMap.put("FUnitID", new VtuzxMap("FNumber", unit));
            colMap.put("FQty", skuCount);
            String flagForFSrcStockID = VtuzxUtil.getString(FID, "flagForFSrcStockID");
            colMap.put("FSrcStockId", new Document("FNumber", flagForFSrcStockID));//调出仓库
            String flagForFDestStockId = VtuzxUtil.getString(FID, "flagForFDestStockId");
            colMap.put("FDestStockId", new Document("FNumber", flagForFDestStockId));//调入仓库
            colMap.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调出库存装填
            colMap.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));//调入库存状态
            colMap.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
            colMap.put("FOwnerTypeOutId", "BD_OwnerOrg");
            String flagForFOwnerOutId = VtuzxUtil.getString(FID, "flagForFOwnerOutId");
            colMap.put("FOwnerOutId", new Document("FNumber", flagForFOwnerOutId));
            colMap.put("FOwnerTypeId", "BD_OwnerOrg");
            colMap.put("FTaxPrice", price);
            String flagForFOwnerId = VtuzxUtil.getString(FID, "flagForFOwnerId");
            colMap.put("FOwnerId", new Document("FNumber", flagForFOwnerId));
            colMap.put("FBaseUnitId", new VtuzxMap("FNumber", unit));
            colMap.put("FBaseQty", skuCount);
            colMap.put("FISFREE", false);
            colMap.put("FKeeperTypeId", "BD_KeeperOrg");
            String flagForFKeeperId = VtuzxUtil.getString(FID, "flagForFKeeperId");
            colMap.put("FKeeperId", new Document("FNumber", flagForFKeeperId));
            colMap.put("FKeeperTypeOutId", "BD_KeeperOrg");
            String flagForFKeeperOutId = VtuzxUtil.getString(FID, "flagForFKeeperOutId");
            colMap.put("FKeeperOutId", new Document("FNumber", flagForFKeeperOutId));
            colMap.put("FDestMaterialId", new VtuzxMap("FNumber", nofitGoodsNo));
            colMap.put("FSaleUnitId", new VtuzxMap("FNumber", unit));
            colMap.put("FSaleQty", skuCount);
            colMap.put("FSalBaseQty", skuCount);
            colMap.put("FPriceUnitID", new VtuzxMap("FNumber", unit));
            colMap.put("FPriceQty", skuCount);
            colMap.put("FPriceBaseQty", skuCount);
            colMap.put("FTransReserveLink", false);
            colMap.put("FCheckDelivery", false);
            FInStockEntry.add(colMap);
        }
        model.put("FBillEntry", FInStockEntry);
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("IsAutoAdjustField", false);
        param.put("InterationFlags", "");
        param.put("IgnoreInterationFlag", true);
        param.put("IsControlPrecision", false);
        param.put("ValidateRepeatJson", false);
        param.put("Model", model);
        String number = "";
        historyDoc.append("param", new VtuzxMap("STK_TransferDirect", param));
        try {
            List<VtuzxMap> transferList = kingdeeService.save(client, "STK_TransferDirect", param);
            VtuzxMap transferMap = transferList.get(0);
            number = VtuzxUtil.getString(transferMap, "Number");
            kingdeeService.submit(client, "STK_TransferDirect", "0", number);
            kingdeeService.audit(client, "STK_TransferDirect", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
            historyDoc.append("syncTask", true);
        } catch (Exception e) {
            if (e.getMessage().contains("更新库存不成功")) {//如果因为库存原因没有上传成功做一个其他入库后再审核
                VtuzxMap FIDOther = new VtuzxMap();
                String flagForFSrcStockID = VtuzxUtil.getString(FID, "flagForFSrcStockID");
                String flagForFOwnerOutId = VtuzxUtil.getString(FID, "flagForFOwnerOutId");
                if (Objects.equals(flagForFStockOutOrgId, "200")) {
                    FIDOther.append("flagOtherForFSTOCKID", flagForFSrcStockID)
                            .append("flagOtherForFStockOrgId", flagForFOwnerOutId)
                            .append("flagOtherForFSUPPLIERID", "05.0002");
                } else if (Objects.equals(flagForFStockOutOrgId, "100")) {
                    FIDOther.append("flagOtherForFSTOCKID", flagForFSrcStockID)
                            .append("flagOtherForFStockOrgId", flagForFOwnerOutId)
                            .append("flagOtherForFSUPPLIERID", "05.0002");
                } else {
                    throw new VtuzxException(e.getMessage());
                }
                Exception recoveryException = null;
                try{
                    syncKingdeeOtherInBillTask(client, data, FIDOther);
                    kingdeeService.audit(client, "STK_TransferDirect", "0", number, "STK_TransferDirect");
                    historyDoc.append("kingdeeNumber", number);
                    historyDoc.append("syncTask", true);
                } catch (Exception ex) {
                    recoveryException = ex;
                }
                //如果其他入库单异常
                if (recoveryException != null) {
                    VtuzxException finalException = new VtuzxException("库存更新失败，且创建其他入库单仍异常: " + recoveryException.getMessage());
                    finalException.initCause(e);
                    throw finalException;
                }
            } else {
                //如果不是更新库存不成功的异常,直接抛出
                throw new VtuzxException(e.getMessage());
            }
        }
    }

    @Override
    public VtuzxMap getStorageOutList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String goodsdocNo = VtuzxUtil.getString(param, "goodsdocNo");
        String channelName = VtuzxUtil.getString(param, "channelName");
        Criteria cond = new Criteria();
        if (!VtuzxUtil.isEmpty(goodsdocNo)) {
            cond.and("goodsdocNo").regex(goodsdocNo);
        }
        if (!VtuzxUtil.isEmpty(channelName)) {
            cond.and("channelName").regex(channelName);
        }
        VtuzxPage page = storageOutDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("goodsdocNo", VtuzxUtil.getString(doc, "goodsdocNo"))//出库单号
                .append("gmtCreate", VtuzxUtil.getString(doc, "gmtCreate"))
                .append("vendCustomerName", VtuzxUtil.getString(doc, "vendCustomerName"))//往来单位名称
                .append("warehouseName", VtuzxUtil.getString(doc, "warehouseName"))//仓库名称
                .append("channelName", VtuzxUtil.getString(doc, "channelName"))//渠道
                .append("inouttypeName", VtuzxUtil.getString(doc, "inouttypeName"))//出库类型
                .append("comment", VtuzxUtil.getString(doc, "comment"))//备注
                .append("inNo", VtuzxUtil.getString(doc, "inNo"))//入库申请单号
                .append("message", VtuzxUtil.getString(doc, "message"))
                .append("syncInfo", VtuzxUtil.getBoolean(doc, "syncInfo"))//传单结果
                .append("companyName", VtuzxUtil.getString(doc, "companyName"))
                .append("inOutReason", VtuzxUtil.getString(doc, "inOutReason")));//出库原因

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public VtuzxMap uploadKingdeeStorageOut(ObjectId userId, List<String> billNoList) throws Exception {
        Iterator<Document> storageOutItr = storageOutDao.findList(Criteria.where("billNo").in(billNoList), null, 0, 0);
        List<Document> storageList = new ArrayList<>();
        while (storageOutItr.hasNext()) {
            Document storageDoc = storageOutItr.next();
            storageList.add(storageDoc);
        }
        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
        for (Document storageDoc : storageList) {
            String gmtCreate = VtuzxUtil.getString(storageDoc, "gmtCreate");//创建日期
            String goodsdocNo = VtuzxUtil.getString(storageDoc, "goodsdocNo");//出库单号
            List<Map<String, Object>> goodsDocDetailList = VtuzxUtil.getObject(storageDoc, "goodsDocDetailList");//物料明细信息

            Map<String, Object> model = new LinkedHashMap<>();//金蝶其它出库model
            model.put("FID", 0);//实体主键
            model.put("FBillTypeID", new Document("FNUMBER", "QTCKD01_SYS"));//单据类型标准其它出出库单
            model.put("FStockOrgId", new Document("FNumber", "100"));//库存组织，开发销售测试
            model.put("FPickOrgId", new Document("FNumber", "100"));//领用组织
            model.put("FStockDirect", "GENERAL");//库存方向（普通）
            model.put("FDate", gmtCreate);//日期
            model.put("FCustId", new Document("FNumber", "CUST0041"));//客户野象
            model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
            model.put("FOwnerIdHead", new Document("FNumber", "100"));//货主
            model.put("FNote", goodsdocNo);//备注，先存放极客云出库单号
            model.put("FBaseCurrId", new Document("FNumber", "PRE001"));//本位币

            List<Map<String, Object>> FEntity = new ArrayList<>();//其它出库体数据
            //循环添加物料信息
            for (Map<String, Object> good : goodsDocDetailList) {
                String goodsNo = VtuzxUtil.getString(good, "goodsNo");//货品编号
                String unitName = VtuzxUtil.getString(good, "unitName");//单位名称
                int quantity = VtuzxUtil.getInt(good, "quantity");//数量
                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",//单位编码
                        "FNAME"//单位名称
                ), cond);
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }
                Map<String, Object> entry = new LinkedHashMap<>();
                entry.put("FMaterialId", new Document("FNumber", goodsNo));//物料编号
                entry.put("FUnitID", new Document("FNumber", unit));//单位
                entry.put("FQty", quantity);//实发数量
                entry.put("FBaseUnitId", new Document("FNumber", unit));//基本单位
                entry.put("FStockId", new Document("FNumber", "yx001"));//发货仓库先固定野象001
                entry.put("FLot", new Document("FNumber", "88888"));//批号先默认
                entry.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                entry.put("FOwnerId", new Document("FNumber", "100"));//货主
                entry.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                entry.put("FKeeperTypeId", "BD_KeeperOrg");//保管者类型
                entry.put("FDistribution", false);//参加费用分配
                entry.put("FKeeperId", new Document("FNumber", "100"));//保管者
                FEntity.add(entry);
            }
            model.put("FEntity", FEntity);
            Map<String, Object> kneeParam = new LinkedHashMap<>();
            kneeParam.put("NeedUpDateFields", new ArrayList<>());
            kneeParam.put("NeedReturnFields", new ArrayList<>());
            kneeParam.put("IsDeleteEntry", true);
            kneeParam.put("SubSystemId", "");
            kneeParam.put("IsVerifyBaseDataField", true);
            kneeParam.put("IsEntryBatchFill", false);
            kneeParam.put("ValidateFlag", true);
            kneeParam.put("NumberSearch", true);
            kneeParam.put("InterationFlags", "");
            kneeParam.put("Model", model);
            //传金蝶其它出
            try {
                List<VtuzxMap> customerList = kingdeeService.save(client, "STK_MisDelivery", kneeParam);
                VtuzxMap kingdeeCustomerMap = customerList.get(0);
                String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
                kingdeeService.submit(client, "STK_MisDelivery", "0", number);
                kingdeeService.audit(client, "STK_MisDelivery", "0", number, "STK_InvCheckResult");
            } catch (Exception e) {
                _logger.info(e.getMessage());
            }
            String _id = VtuzxUtil.getString(storageDoc, "_id");
            storageOutDao.updateById(_id, new Document("isUpload", "yes"));
        }
        return new VtuzxMap();
    }

    /**
     * 获取极客云调拨单
     *
     * @param userId
     * @param param
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public VtuzxMap getjkyAllocation(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {

        Criteria cond = new Criteria();
        VtuzxPage page = jikeyunAllocationDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("billNo", VtuzxUtil.getString(doc, "billNo"))
                .append("allocateNo", VtuzxUtil.getString(doc, "allocateNo"))//极客云调拨单号
                .append("outWarehouseName", VtuzxUtil.getString(doc, "outWarehouseName"))//调出仓库
                .append("intWarehouseName", VtuzxUtil.getString(doc, "intWarehouseName"))//调入仓库
                .append("allocateTypeName", VtuzxUtil.getString(doc, "allocateTypeName"))//调拨类型
                .append("applyUserName", VtuzxUtil.getString(doc, "applyUserName"))//申请人姓名
                .append("operator", VtuzxUtil.getString(doc, "operator"))//制单人
                .append("isUpload", VtuzxUtil.getString(doc, "isUpload"))
                .append("skuCount", VtuzxUtil.getDouble(doc, "skuCount"))//货品数量
                .append("gmtCreate", new Date(VtuzxUtil.getLong(doc, "gmtCreate"))));//创建时间

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public VtuzxMap getJikeyunSale(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String tradeNo = VtuzxUtil.getString(param, "tradeNo");
        String shopName = VtuzxUtil.getString(param, "shopName");
        String isUpload = VtuzxUtil.getString(param, "isUpload");
        List<String> consignTime = VtuzxUtil.getObject(param, "consignTime");
        Criteria cond = new Criteria();
        //晓芹公司的
        cond.and("companyName").regex("晓芹");
        if (!VtuzxUtil.isEmpty(tradeNo)) {
            cond.and("tradeNo").regex(tradeNo);
        }
        if (!VtuzxUtil.isEmpty(shopName)) {
            cond.and("shopName").regex(shopName);
        }
        if (!VtuzxUtil.isEmpty(isUpload)) {
            cond.and("isUpload").is(isUpload);
        }
        if (!VtuzxUtil.isEmpty(consignTime)) {
            cond.and("consignTime").gte(VtuzxUtil.parseDate(consignTime.get(0))).lte(VtuzxUtil.parseDate(consignTime.get(1) + " 23:59:59"));
        }
        VtuzxPage page = jikeyunSaleDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("billNo", VtuzxUtil.getString(doc, "billNo"))
                .append("customerName", VtuzxUtil.getString(doc, "customerName"))//客户名称
                .append("customerAccount", VtuzxUtil.getString(doc, "customerAccount"))//客户账号
                .append("payment", VtuzxUtil.getDouble(doc, "payment"))//原订单金额
                .append("settleFee", VtuzxUtil.getDouble(doc, "settleFee"))//结算金额
                .append("settleTime", VtuzxUtil.formatYmdHmsF(VtuzxUtil.getObject(doc, "settleTime")))//结算日期
                .append("consignTime", VtuzxUtil.formatYmdHmsF(VtuzxUtil.getObject(doc, "consignTime")))//发货日期
                .append("tradeNo", VtuzxUtil.getString(doc, "tradeNo"))//订单编号
                .append("flagNames", VtuzxUtil.getString(doc, "flagNames"))//标记名称
                .append("shopName", VtuzxUtil.getString(doc, "shopName"))//店铺名称
                .append("tradeCount", VtuzxUtil.getDouble(doc, "tradeCount"))//订单总数量
                .append("isUpload", VtuzxUtil.getString(doc, "isUpload"))
                .append("sellerMemo", VtuzxUtil.getString(doc, "sellerMemo")));//备注
        List<String> tradeNoList = new ArrayList<>();
        for (VtuzxMap data : dataList) {
            String trade = VtuzxUtil.getString(data, "tradeNo");
            tradeNoList.add(trade);
        }
        List<Document> innersetList = new ArrayList<>();
        Iterator<Document> innersetItr = innersettorderDao.findList(Criteria.where("sourceBillNo").in(tradeNoList), null, 0, 0);
        while (innersetItr.hasNext()) {
            Document innerSsetDoc = innersetItr.next();
            innersetList.add(innerSsetDoc);
        }
        for (VtuzxMap data : dataList) {
            String trade = VtuzxUtil.getString(data, "tradeNo");
            for (Document doc : innersetList) {
                String sourceBillNo = VtuzxUtil.getString(doc, "sourceBillNo");
                if (trade.equals(sourceBillNo)) {
                    String orderNo = VtuzxUtil.getString(doc, "orderNo");
                    String orderUpLoad = VtuzxUtil.getString(doc, "isUpload");
                    data.append("orderNo", orderNo)
                            .append("orderUpLoad", orderUpLoad);
                    break;
                }
            }
        }
        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public VtuzxMap uploadKingdeeAllocation(ObjectId userId, List<String> billNoList) throws VtuzxException {
        Iterator<Document> allocationItr = jikeyunAllocationDao.findList(Criteria.where("billNo").in(billNoList), null, 0, 0);
        List<Document> allocationList = new ArrayList<>();
        while (allocationItr.hasNext()) {
            Document allocationDoc = allocationItr.next();
            allocationList.add(allocationDoc);
        }
        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();

        try {
            syncKingdeeAllocation(client, allocationList);
        } catch (Exception e) {
            _logger.info(e.getMessage());
        }
        return null;
    }

    @Override
    public VtuzxMap uploadKingdeeSale(ObjectId userId, String userName, List<String> billNoList, String orderTime) throws VtuzxException {

        Iterator<Document> allocationItr = jikeyunSaleDao.findList(Criteria.where("tradeNo").in(billNoList), null, 0, 0);
        List<VtuzxMap> saleList = new ArrayList<>();
        while (allocationItr.hasNext()) {
            Document allocationDoc = allocationItr.next();
            String tradeNo = VtuzxUtil.getString(allocationDoc, "tradeNo");
//            Document innerSetterDoc = innersettorderDao.findOne(Criteria.where("sourceBillNo").is(tradeNo));
//            if (VtuzxUtil.isEmpty(innerSetterDoc)){
//                throw new VtuzxException(String.format("没有对应公司间结算单无法上传"));
//            }
//            String orderNo = VtuzxUtil.getString(innerSetterDoc,"orderNo");
//            String isUpload = VtuzxUtil.getString(innerSetterDoc,"isUpload");
//            if ("no".equals(isUpload)){
//                throw new VtuzxException(String.format("结算单号%s还没有上传，无法上传销售单",orderNo));
//            }
            VtuzxMap map = new VtuzxMap(allocationDoc);
            saleList.add(map);
        }

        VtuzxKingdeeCloudClient yeXiangClient = kingdeeService.loginKingdeeYeXiang();//野象
//        VtuzxKingdeeCloudClient yeXiangClient = kingdeeService.loginKingdeeEveryClient(userId,userName);
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));

        for (VtuzxMap data : saleList) {
            String tradeNo = VtuzxUtil.getString(data, "tradeNo");
            String shopName = VtuzxUtil.getString(data, "shopName");//销售渠道
            String companyName = VtuzxUtil.getString(data, "companyName");//公司名称
            String flagNames = VtuzxUtil.getString(data, "flagNames");//标记名称
            double tradeCount = VtuzxUtil.getDouble(data, "tradeCount");
            Document historyDoc = syncOrderDao.findOne(Criteria.where("billNo").is(tradeNo));
            ObjectId id = null;
            if (historyDoc == null) {
                historyDoc = new Document("billNo", tradeNo);
            } else {
                id = VtuzxUtil.getObject(historyDoc, "_id");
            }
            historyDoc.append("billNo", tradeNo);
            historyDoc.append("userId", userId);
            historyDoc.append("userName", userName);
            historyDoc.append("source", "source");
            historyDoc.append("data", data);
            historyDoc.append("event", "jackYunSaleOut");
            historyDoc.append("orderTime", orderTime);
            String success = "";//方法返回信息
            try {
                if (companyName.contains("百年晓芹")) {
                    if (tradeCount >= 0) { //销售出
                        //销售出之前做一个其他入库,避免库存不足
                        //查询当前订单是否在金蝶存在
                        String cond = String.format("F_PSUH_XSDH = '%s'", tradeNo);
                        List<VtuzxMap> saleOrder = kingdeeService.query(yeXiangClient, "SAL_OUTSTOCK", new VtuzxArrayList<>(
                                "FBillNo"//单据编号
                        ), cond);
                        //说明已经传过,跳过当前循环
                        if (saleOrder != null && saleOrder.size() > 0) {
                            continue;
                        }

                        success = syncKingdeeSaleOutOne(yeXiangClient, data, historyDoc, storeDoc);
                    } else {//负数传野象销售退

                        String cond = String.format("F_PSUH_XSDH = '%s'", tradeNo);
                        List<VtuzxMap> saleOrder = kingdeeService.query(yeXiangClient, "SAL_RETURNSTOCK", new VtuzxArrayList<>(
                                "FBillNo"//单据编号
                        ), cond);
                        //说明已经传过,跳过当前循环
                        if (saleOrder != null && saleOrder.size() > 0) {
                            continue;
                        }
                        syncKingdeeSaleReturnYX(yeXiangClient, data, historyDoc);
                    }

                } else if (companyName.contains("晓芹")) {
                    if (tradeCount >= 0) {
//                            syncKingdeeSaleOutXQ(client,data,historyDoc);
                    } else {//负数传销售退
//                            syncKingdeeSaleReturnXQ(client,data,historyDoc);
                    }

                }

                //如果方法有返回值,说明有问题
                if (!VtuzxUtil.isEmpty(success)) {
                    historyDoc.append("success", false);
                    if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {
                        historyDoc.remove("_id");
                        historyDoc.append("updateUserId", userId);
                        historyDoc.append("updateUserName", userName);
                        syncOrderDao.updateById(id, historyDoc);
                    }

                    String _id = VtuzxUtil.getString(data, "_id");
                    jikeyunSaleDao.updateById(_id, new Document("isUpload", "no"));
                } else {
                    historyDoc.append("success", true);
                    if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {
                        historyDoc.remove("id");
                        historyDoc.remove("createTime");
                        historyDoc.remove("updateTime");
                        //不知道为啥remove删除字段后还有信息
                        historyDoc.append("message", "");
                        historyDoc.append("updateUserId", userId);
                        historyDoc.append("updateUserName", userName);
                        syncOrderDao.updateById(id, historyDoc);
                    }
                    String _id = VtuzxUtil.getString(data, "_id");
                    jikeyunSaleDao.updateById(_id, new Document("isUpload", "yes"));
                }

            } catch (Exception e) {
                //因为物料编码原因没传成功的给与提示
                if (e.getMessage().contains("物料编码")) {
                    historyDoc.append("prdInStockStock", false).append("message", e.getMessage() + "请到中台同步物料").append("success", false);
                } else if (e.getMessage().contains("仓库")) {
                    historyDoc.append("prdInStockStock", false).append("message", "金蝶没有对应仓库,请维护").append("success", false);
                } else {
                    historyDoc.append("prdInStockStock", false).append("message", e.getMessage()).append("success", false);
                }

                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    syncOrderDao.updateById(id, historyDoc);
                }

                _logger.info(e.getMessage());
//                throw new VtuzxException(e.getMessage());

            }

        }

        return null;
    }

    /**
     * 通过网店订单号传吉客云销售单到金蝶
     *
     * @param userId
     * @param userName
     * @param billNoList
     * @return
     * @throws VtuzxException
     */
    private VtuzxMap uploadKingdeeSaleByOnline(ObjectId userId, String userName, List<String> billNoList) throws VtuzxException {

        Iterator<Document> allocationItr = jikeyunSaleDao.findList(Criteria.where("onlineTradeNo").in(billNoList), null, 0, 0);
        List<VtuzxMap> saleList = new ArrayList<>();
        while (allocationItr.hasNext()) {
            Document allocationDoc = allocationItr.next();
//            String uploadStatus = VtuzxUtil.getString(allocationDoc,"isUpload");//是否上传
//            //如果上传过的跳过
//            if("yes".equals(uploadStatus)){
//                continue;
//            }
            String tradeNo = VtuzxUtil.getString(allocationDoc, "tradeNo");
//            Document innerSetterDoc = innersettorderDao.findOne(Criteria.where("sourceBillNo").is(tradeNo));
//            if (VtuzxUtil.isEmpty(innerSetterDoc)){
//                throw new VtuzxException(String.format("没有对应公司间结算单无法上传"));
//            }
//            String orderNo = VtuzxUtil.getString(innerSetterDoc,"orderNo");
//            String isUpload = VtuzxUtil.getString(innerSetterDoc,"isUpload");
//            if ("no".equals(isUpload)){
//                throw new VtuzxException(String.format("结算单号%s还没有上传，无法上传销售单",orderNo));
//            }
            VtuzxMap map = new VtuzxMap(allocationDoc);
            saleList.add(map);
        }

        VtuzxKingdeeCloudClient yeXiangClient = kingdeeService.loginKingdeeYeXiang();//野象
        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();//晓芹
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));

        for (VtuzxMap data : saleList) {
            String tradeNo = VtuzxUtil.getString(data, "tradeNo");
            String onlineTradeNo = VtuzxUtil.getString(data, "onlineTradeNo");//网店订单号
            String shopName = VtuzxUtil.getString(data, "shopName");//销售渠道
            String companyName = VtuzxUtil.getString(data, "companyName");//公司名称
            String flagNames = VtuzxUtil.getString(data, "flagNames");//标记名称
            double tradeCount = VtuzxUtil.getDouble(data, "tradeCount");
            Document historyDoc = syncOrderDao.findOne(Criteria.where("billNo").is(onlineTradeNo));
            ObjectId id = null;
            if (historyDoc == null) {
                historyDoc = new Document("billNo", onlineTradeNo);
            } else {
                id = VtuzxUtil.getObject(historyDoc, "_id");
            }
            historyDoc.append("billNo", onlineTradeNo);
            historyDoc.append("userId", userId);
            historyDoc.append("userName", userName);
            historyDoc.append("source", "source");
            historyDoc.append("data", data);
            historyDoc.append("event", "jackYunSaleOut");

            String success = "";//方法返回信息
            try {
                if (companyName.contains("野象")) {
                    if (tradeCount >= 0) { //销售出
                        //销售出之前做一个其他入库,避免库存不足
                        //查询当前订单是否在金蝶存在
                        String cond = String.format("F_PSUH_XSDH = '%s'", tradeNo);
                        List<VtuzxMap> saleOrder = kingdeeService.query(yeXiangClient, "SAL_OUTSTOCK", new VtuzxArrayList<>(
                                "FBillNo"//单据编号
                        ), cond);
                        //说明已经传过,跳过当前循环
                        if (saleOrder != null && saleOrder.size() > 0) {
                            continue;
                        }

                        success = syncKingdeeSaleOutOne(yeXiangClient, data, historyDoc, storeDoc);
                    } else {//负数传野象销售退

                        String cond = String.format("F_PSUH_XSDH = '%s'", tradeNo);
                        List<VtuzxMap> saleOrder = kingdeeService.query(yeXiangClient, "SAL_RETURNSTOCK", new VtuzxArrayList<>(
                                "FBillNo"//单据编号
                        ), cond);
                        //说明已经传过,跳过当前循环
                        if (saleOrder != null && saleOrder.size() > 0) {
                            continue;
                        }
                        syncKingdeeSaleReturnYX(yeXiangClient, data, historyDoc);
                    }

                }

                //如果方法有返回值,说明有问题
                if (!VtuzxUtil.isEmpty(success)) {
                    historyDoc.append("success", false);
                    if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {
                        historyDoc.remove("_id");
                        historyDoc.append("updateUserId", userId);
                        historyDoc.append("updateUserName", userName);
                        syncOrderDao.updateById(id, historyDoc);
                    }

                    String _id = VtuzxUtil.getString(data, "_id");
                    jikeyunSaleDao.updateById(_id, new Document("isUpload", "no"));
                } else {
                    historyDoc.append("success", true);
                    if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {
                        historyDoc.remove("id");
                        historyDoc.remove("createTime");
                        historyDoc.remove("updateTime");
                        //不知道为啥remove删除字段后还有信息
                        historyDoc.append("message", "");
                        historyDoc.append("updateUserId", userId);
                        historyDoc.append("updateUserName", userName);
                        syncOrderDao.updateById(id, historyDoc);
                    }
                    String _id = VtuzxUtil.getString(data, "_id");
                    jikeyunSaleDao.updateById(_id, new Document("isUpload", "yes"));
                }


            } catch (Exception e) {
                //因为物料编码原因没传成功的给与提示
                if (e.getMessage().contains("物料编码")) {
                    historyDoc.append("prdInStockStock", false).append("message", e.getMessage() + "请到中台同步物料").append("success", false);
                } else if (e.getMessage().contains("仓库")) {
                    historyDoc.append("prdInStockStock", false).append("message", "金蝶没有对应仓库,请维护").append("success", false);
                } else {
                    historyDoc.append("prdInStockStock", false).append("message", e.getMessage()).append("success", false);
                }

                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    syncOrderDao.updateById(id, historyDoc);
                }

                _logger.info(e.getMessage());
//                throw new VtuzxException(e.getMessage());

            }

        }

        return null;
    }

    /**
     * 野象其他入库单,避免传销售出库单时没有库存
     *
     * @param yeXiangClient
     * @param data
     * @param historyDoc
     * @param storeDoc
     */
    private void syncKingdeeOtherInBill(VtuzxKingdeeCloudClient yeXiangClient, VtuzxMap data, Document historyDoc, Document storeDoc) throws Exception {
        Map<String, Object> otherInOrderParam = new LinkedHashMap<>();
        Map<String, Object> otherInOrderModel = new LinkedHashMap<>();
        List<Map<String, Object>> otherInOrderMapList = new ArrayList<>();
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        //循环货品集合，添加金蝶单据体信息
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }

            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //在同步单据的时候会查询仓库id
        String stockId = VtuzxUtil.getString(data, "stockId");
        //添加单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        //查询单位编码，直接传文字无效
                        String unit = (String) unitMap.get(unitName);
                        Map<String, Object> otherInOrderMap = new LinkedHashMap<>();
                        otherInOrderMap.put("FMATERIALID", new VtuzxMap("FNumber", goodsNo));
                        otherInOrderMap.put("FUnitID", new VtuzxMap("FNumber", unit));
                        otherInOrderMap.put("FQty", skuCount);
                        otherInOrderMap.put("FSTOCKID", new VtuzxMap("FNumber", stockId));
                        otherInOrderMap.put("FSTOCKSTATUSID", new VtuzxMap("FNumber", "KCZT01_SYS"));
                        otherInOrderMapList.add(otherInOrderMap);

                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                //查询单位编码，直接传文字无效
                String unit = (String) unitMap.get(unitName);
                Map<String, Object> otherInOrderMap = new LinkedHashMap<>();
                otherInOrderMap.put("FMATERIALID", new VtuzxMap("FNumber", goodsNo));
                otherInOrderMap.put("FUnitID", new VtuzxMap("FNumber", unit));
                otherInOrderMap.put("FQty", skuCount);
                otherInOrderMap.put("FSTOCKID", new VtuzxMap("FNumber", stockId));
                otherInOrderMap.put("FSTOCKSTATUSID", new VtuzxMap("FNumber", "KCZT01_SYS"));
                otherInOrderMapList.add(otherInOrderMap);
            }
        }

//        for (String key : materialMap.keySet()) {
//            VtuzxMap dataMap = (VtuzxMap) materialMap.get(key);
//            Map<String, Object> otherInOrderMap = new LinkedHashMap<>();
//            String materialNo = VtuzxUtil.getString(dataMap, "goodsNo");
//            String unitName = VtuzxUtil.getString(dataMap, "unitName");
//            double skuCount = VtuzxUtil.getDouble(dataMap, "skuCount");
//            //在同步单据的时候会查询仓库id
//            String stockId = VtuzxUtil.getString(data,"stockId");
//            //查询单位编码，直接传文字无效
//            String cond = String.format("Fname = '%s'", unitName);
//            List<VtuzxMap> bd_customer = kingdeeService.query(yeXiangClient, "BD_UNIT", new VtuzxArrayList<>(
//                    "FNumber",//物料编码
//                    "FNAME"//物料名称
//            ), cond);
//            //获取物料编码
//            String unit = "";
//            if (bd_customer != null && bd_customer.size() > 0) {
//                unit = bd_customer.get(0).getString("FNumber");
//            }
//
//            otherInOrderMap.put("FMATERIALID", new VtuzxMap("FNumber", materialNo));
//            otherInOrderMap.put("FUnitID", new VtuzxMap("FNumber", unit));
//            otherInOrderMap.put("FQty", skuCount);
//            otherInOrderMap.put("FSTOCKID", new VtuzxMap("FNumber", stockId));
//            otherInOrderMap.put("FSTOCKSTATUSID", new VtuzxMap("FNumber", "KCZT01_SYS"));
//            otherInOrderMapList.add(otherInOrderMap);
//        }
        otherInOrderModel.put("FSUPPLIERID", new VtuzxMap("FNumber", "05.0002"));

        otherInOrderModel.put("FNOTE", tradeNo);//备注

        otherInOrderModel.put("FEntity", otherInOrderMapList);

        otherInOrderParam.put("NeedUpDateFields", new ArrayList<>());
        otherInOrderParam.put("NeedReturnFields", new ArrayList<>());
        otherInOrderParam.put("IsDeleteEntry", false);
        otherInOrderParam.put("SubSystemId", "");
        otherInOrderParam.put("IsVerifyBaseDataField", false);
        otherInOrderParam.put("IsEntryBatchFill", true);
        otherInOrderParam.put("ValidateFlag", true);
        otherInOrderParam.put("NumberSearch", true);
        otherInOrderParam.put("InterationFlags", "");
        otherInOrderParam.put("Model", otherInOrderModel);
        try {
            List<VtuzxMap> otherInList = kingdeeService.save(yeXiangClient, "STK_MISCELLANEOUS", otherInOrderParam);
            VtuzxMap otherInMap = otherInList.get(0);
            String number = VtuzxUtil.getString(otherInMap, "Number");
            kingdeeService.submit(yeXiangClient, "STK_MISCELLANEOUS", "0", number);
            kingdeeService.audit(yeXiangClient, "STK_MISCELLANEOUS", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            _logger.info(e.getMessage());
        }
    }

    /**
     * 野象其他入库单,避免传销售出库单时没有库存Task
     *
     * @param client
     * @param data
     */
    private void syncKingdeeOtherInBillTask(VtuzxKingdeeCloudClient client, Document data, VtuzxMap FIDOther) throws Exception {
        Map<String, Object> otherInOrderParam = new LinkedHashMap<>();
        Map<String, Object> otherInOrderModel = new LinkedHashMap<>();
        List<Map<String, Object>> otherInOrderMapList = new ArrayList<>();
        List<Document> goodsList;
        if (!VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "allocateNo"))) {
            goodsList = VtuzxUtil.getObject(data, "stockAllocateDetailViews");
        } else {
            goodsList = VtuzxUtil.getObject(data, "goodsDetail");
        }
        String jsonString = JSON.toJSONString(goodsList);
        List<Map<String, Object>> goodsDetailList = JSONArray.parseObject(jsonString, List.class);
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        String allocateNo = VtuzxUtil.getString(data, "allocateNo");//调拨单号
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
            String GoodsNo = VtuzxUtil.getString(doc, "GoodsNo");
            Document getGoods;
            if (!VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "allocateNo"))) {
                getGoods = (Document) goodsMap.get(goodsNo);
                if (!materialNoList.contains(goodsNo)) {
                    materialNoList.add(goodsNo);
                }
                if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                    goodsMap.put(goodsNo, doc);
                } else {
                    int skuCount = VtuzxUtil.getInt(doc, "skuCount");
                    int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                    doc.replace("skuCount", skuCount + skuNowCount);
                    goodsMap.put(goodsNo, doc);
                }
            } else {
                getGoods = (Document) goodsMap.get(GoodsNo);
                if (!materialNoList.contains(GoodsNo)) {
                    materialNoList.add(GoodsNo);
                }
                if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                    goodsMap.put(GoodsNo, doc);
                } else {
                    int SellCount = VtuzxUtil.getInt(doc, "SellCount");
                    int sellNowCount = VtuzxUtil.getInt(getGoods, "SellCount");
                    doc.replace("SellCount", SellCount + sellNowCount);
                    goodsMap.put(GoodsNo, doc);
                }
            }
        }
        //循环货品集合，添加金蝶单据体信息
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsDetailList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //在同步单据的时候会查询仓库id
//        String stockId = VtuzxUtil.getString(data,"outWarehouseId");
        //添加单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        //查询单位编码，直接传文字无效
                        String unit = (String) unitMap.get(unitName);
                        Map<String, Object> otherInOrderMap = new LinkedHashMap<>();
                        otherInOrderMap.put("FMATERIALID", new VtuzxMap("FNumber", goodsNo));
                        otherInOrderMap.put("FUnitID", new VtuzxMap("FNumber", unit));
                        otherInOrderMap.put("FQty", skuCount);
                        String flagOtherForFSTOCKID = VtuzxUtil.getString(FIDOther, "flagOtherForFSTOCKID");
                        otherInOrderMap.put("FSTOCKID", new Document("FNumber", flagOtherForFSTOCKID));//仓库
                        otherInOrderMap.put("FSTOCKSTATUSID", new VtuzxMap("FNumber", "KCZT01_SYS"));
                        otherInOrderMapList.add(otherInOrderMap);
                    }
                }
            } else {
                String goodsNo;
                String unitName;
                double skuCount;
                if (!VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "allocateNo"))) {
                    goodsNo = VtuzxUtil.getString(doc, "goodsNo");
                    unitName = VtuzxUtil.getString(doc, "unitName");
                    skuCount = VtuzxUtil.getDouble(doc, "skuCount");
                } else {
                    goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                    unitName = VtuzxUtil.getString(doc, "Unit");
                    skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                }
                //查询单位编码，直接传文字无效
                String unit = (String) unitMap.get(unitName);

                //===获取金蝶物料单位===
                String floatCond = String.format("FNumber = '%s'", goodsNo);
                List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FBaseUnitId.FNumber"
                ), floatCond);
                if (bd_Material != null && bd_Material.size() > 0) {
                    unit = bd_Material.get(0).getString("FBaseUnitId.FNumber");
                }
                //===获取金蝶物料单位===

                Map<String, Object> otherInOrderMap = new LinkedHashMap<>();
                otherInOrderMap.put("FMATERIALID", new VtuzxMap("FNumber", goodsNo));
                otherInOrderMap.put("FUnitID", new VtuzxMap("FNumber", unit));
                otherInOrderMap.put("FQty", skuCount);
                String flagOtherForFSTOCKID = VtuzxUtil.getString(FIDOther, "flagOtherForFSTOCKID");
                otherInOrderMap.put("FSTOCKID", new Document("FNumber", flagOtherForFSTOCKID));//仓库
                otherInOrderMap.put("FSTOCKSTATUSID", new VtuzxMap("FNumber", "KCZT01_SYS"));
                otherInOrderMapList.add(otherInOrderMap);
            }
        }
        String flagOtherForFSUPPLIERID = VtuzxUtil.getString(FIDOther, "flagOtherForFSUPPLIERID");
        otherInOrderModel.put("FSUPPLIERID", new Document("FNumber", flagOtherForFSUPPLIERID));//供应商
        if (!VtuzxUtil.isEmpty(allocateNo)) {
            otherInOrderModel.put("FNOTE", allocateNo);//备注
        } else {
            otherInOrderModel.put("FNOTE", tradeNo);//备注
        }
        otherInOrderModel.put("FEntity", otherInOrderMapList);
        String flagOtherForFStockOrgId = VtuzxUtil.getString(FIDOther, "flagOtherForFStockOrgId");
        otherInOrderModel.put("FStockOrgId", new Document("FNumber", flagOtherForFStockOrgId));//收货组织
        otherInOrderParam.put("NeedUpDateFields", new ArrayList<>());
        otherInOrderParam.put("NeedReturnFields", new ArrayList<>());
        otherInOrderParam.put("IsDeleteEntry", false);
        otherInOrderParam.put("SubSystemId", "");
        otherInOrderParam.put("IsVerifyBaseDataField", false);
        otherInOrderParam.put("IsEntryBatchFill", true);
        otherInOrderParam.put("ValidateFlag", true);
        otherInOrderParam.put("NumberSearch", true);
        otherInOrderParam.put("InterationFlags", "");
        otherInOrderParam.put("Model", otherInOrderModel);
        try {
            List<VtuzxMap> otherInList = kingdeeService.save(client, "STK_MISCELLANEOUS", otherInOrderParam);
            VtuzxMap otherInMap = otherInList.get(0);
            String number = VtuzxUtil.getString(otherInMap, "Number");
            kingdeeService.submit(client, "STK_MISCELLANEOUS", "0", number);
            kingdeeService.audit(client, "STK_MISCELLANEOUS", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            _logger.info(e.getMessage());
        }
    }

    /**
     * 金蝶销售订单
     *
     * @param yeXiangClient
     * @param data
     * @param historyDoc
     * @param storeDoc      吉客云token
     * @throws Exception
     */
    private String syncKingdeeSaleOrderYx(VtuzxKingdeeCloudClient yeXiangClient, VtuzxMap data, Document historyDoc, Document storeDoc) throws Exception {
        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data, "customerName");//客户名称
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");
        String shopName = VtuzxUtil.getString(data, "shopName");
        String customerId = getCustomer(customerCode, yeXiangClient, storeDoc, customerName);//获取到传金蝶的客户编号
        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        if (VtuzxUtil.isEmpty(channelDoc)) {
            historyDoc.append("message", "无法查询到渠道,请维护渠道");
            return "无法查询到渠道,请维护渠道";
        }
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        Map<String, Object> model = new LinkedHashMap<>();//金蝶销售订单model
        model.put("Fid", 0);
        model.put("FBillTypeID", new Document("FNumber", "XSDD01_SYS"));
        model.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        model.put("FCustId", new Document("FNumber", customerId));//客户
        //TODO 暂时先固定一个销售员
        model.put("FSalerId", new Document("FNumber", "0015"));//销售员
        model.put("FSettleId", new Document("FNumber", "04.01.003"));//结算方
        model.put("FChargeId", new Document("FNumber", "04.01.003"));//付款方
        model.put("F_PSUH_SFJC", "1");//是否寄存
        model.put("F_PSUH_jikeyunbiaoji", tradeNo);//吉客云标记暂时传吉客云销售单号
        model.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
        model.put("F_PSUH_XSQD", channelGroup);//销售渠道
        model.put("F_PSUH_DPMC", shopName);//店铺名称
        Map<String, Object> orderFinance = new LinkedHashMap<>();//财务信息参数
        orderFinance.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        orderFinance.put("FIsPriceExcludeTax ", true);//价外税
        orderFinance.put("FIsIncludedTax ", true);//是否含税
        model.put("FSaleOrderFinance", orderFinance);
        List<Map<String, Object>> orderEntity = new ArrayList<>();//物料信息
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");//货品信息
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        //循环货品集合，添加金蝶单据体信息
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        //循环货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "ShareFavourableAfterFee");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        String cond = String.format("Fname = '%s'", unitName);
                        List<VtuzxMap> bd_customer = kingdeeService.query(yeXiangClient, "BD_UNIT", new VtuzxArrayList<>(
                                "FNumber",//物料编码
                                "FNAME"//物料名称
                        ), cond);
                        //获取物料编码
                        String unit = "";
                        if (bd_customer != null && bd_customer.size() > 0) {
                            unit = bd_customer.get(0).getString("FNumber");
                        }

                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//单位
                        colMap.put("FPriceUnitId", new Document("FNumber", unit));//计价单位
                        colMap.put("FTaxPrice ", settPrice / skuCount);//含税单价
                        colMap.put("FPriceUnitQty", skuCount);//计价数量
                        colMap.put("FSettleOrgIds", new Document("FNumber", "100"));//结算组织
                        orderEntity.add(colMap);

                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee");//分摊后金额,对应金蝶含税单价
                double skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(yeXiangClient, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",//物料编码
                        "FNAME"//物料名称
                ), cond);
                //获取物料编码
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }

                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//单位
                colMap.put("FPriceUnitId", new Document("FNumber", unit));//计价单位
//            colMap.put("FPrice",settPrice);//单价
                colMap.put("FTaxPrice ", settPrice / skuCount);//含税单价
                colMap.put("FPriceUnitQty", skuCount);//计价数量
                colMap.put("FSettleOrgIds", new Document("FNumber", "100"));//结算组织
                orderEntity.add(colMap);

            }


        }

        model.put("FSaleOrderEntry", orderEntity);

        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", model);

        historyDoc.append("param", model);
        //创建销售订单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(yeXiangClient, "SAL_SaleOrder", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(yeXiangClient, "SAL_SaleOrder", "0", number);
            kingdeeService.audit(yeXiangClient, "SAL_SaleOrder", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(e.getMessage());
            throw new VtuzxException(e.getMessage());
        }
        return "";
    }

    @Override
    public VtuzxMap getJikeyunSaleYX(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String tradeNo = VtuzxUtil.getString(param, "tradeNo");
        String onlineTradeNo = VtuzxUtil.getString(param, "onlineTradeNo");
        String shopName = VtuzxUtil.getString(param, "shopName");
        String flagNames = VtuzxUtil.getString(param, "flagNames");
        String isUpload = VtuzxUtil.getString(param, "isUpload");
        List<String> consignTime = VtuzxUtil.getObject(param, "consignTime");
        List<String> gmtCreate = VtuzxUtil.getObject(param, "gmtCreate");
        List<String> completeTime = VtuzxUtil.getObject(param, "completeTime");//完成时间

        Criteria cond = new Criteria();
        //晓芹公司的
        cond.and("companyName").regex("百年晓芹");
        if (!VtuzxUtil.isEmpty(tradeNo)) {
            cond.and("tradeNo").regex(tradeNo);
        }
        if (!VtuzxUtil.isEmpty(onlineTradeNo)) {
            cond.and("onlineTradeNo").regex(onlineTradeNo);
        }
        if (!VtuzxUtil.isEmpty(flagNames)) {
            cond.and("flagNames").regex(flagNames);
        }
        if (!VtuzxUtil.isEmpty(shopName)) {
            cond.and("shopName").regex(shopName);
        }
        if (!VtuzxUtil.isEmpty(isUpload)) {
            cond.and("isUpload").is(isUpload);
        }
        if (!VtuzxUtil.isEmpty(consignTime)) {
            cond.and("consignTime").gte(VtuzxUtil.parseDate(consignTime.get(0))).lte(VtuzxUtil.parseDate(consignTime.get(1) + " 23:59:59"));
        }
        if (!VtuzxUtil.isEmpty(gmtCreate)) {
            cond.and("gmtCreate").gte(VtuzxUtil.parseDate(gmtCreate.get(0))).lte(VtuzxUtil.parseDate(gmtCreate.get(1) + " 23:59:59"));
        }
        if (!VtuzxUtil.isEmpty(completeTime)) {
            cond.and("completeTime").gte(completeTime.get(0)).lte(completeTime.get(1) + " 23:59:59");
        }
        VtuzxPage page = jikeyunSaleDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("billNo", VtuzxUtil.getString(doc, "billNo"))
                .append("onlineTradeNo", VtuzxUtil.getString(doc, "onlineTradeNo"))
                .append("customerName", VtuzxUtil.getString(doc, "customerName"))//客户名称
                .append("customerAccount", VtuzxUtil.getString(doc, "customerAccount"))//客户账号
                .append("payment", VtuzxUtil.getDouble(doc, "payment"))//原订单金额
                .append("settleFee", VtuzxUtil.getDouble(doc, "settleFee"))//结算金额
                .append("settleTime", VtuzxUtil.formatYmdHmsF(VtuzxUtil.getObject(doc, "settleTime")))//结算日期
                .append("consignTime", VtuzxUtil.formatYmdHmsF(VtuzxUtil.getObject(doc, "consignTime")))//发货日期
//                .append("gmtCreate",VtuzxUtil.getString(doc,"gmtCreate"))//吉客云创建时间
                .append("tradeNo", VtuzxUtil.getString(doc, "tradeNo"))//订单编号
                .append("flagNames", VtuzxUtil.getString(doc, "flagNames"))//标记名称
                .append("shopName", VtuzxUtil.getString(doc, "shopName"))//店铺名称
                .append("tradeCount", VtuzxUtil.getDouble(doc, "tradeCount"))//订单总数量
                .append("isUpload", VtuzxUtil.getString(doc, "isUpload"))
                .append("companyName", VtuzxUtil.getString(doc, "companyName"))
                .append("completeTime", VtuzxUtil.getString(doc, "completeTime"))//完成时间
                .append("sellerMemo", VtuzxUtil.getString(doc, "sellerMemo")));//备注
        List<String> tradeNoList = new ArrayList<>();
        for (VtuzxMap data : dataList) {
            String trade = VtuzxUtil.getString(data, "tradeNo");
            tradeNoList.add(trade);
        }
        List<Document> innersetList = new ArrayList<>();
        Iterator<Document> innersetItr = innersettorderDao.findList(Criteria.where("sourceBillNo").in(tradeNoList), null, 0, 0);
        while (innersetItr.hasNext()) {
            Document innerSsetDoc = innersetItr.next();
            innersetList.add(innerSsetDoc);
        }
        for (VtuzxMap data : dataList) {
            String trade = VtuzxUtil.getString(data, "tradeNo");
            for (Document doc : innersetList) {
                String sourceBillNo = VtuzxUtil.getString(doc, "sourceBillNo");
                if (trade.equals(sourceBillNo)) {
                    String orderNo = VtuzxUtil.getString(doc, "orderNo");
                    String orderUpLoad = VtuzxUtil.getString(doc, "isUpload");
                    data.append("orderNo", orderNo)
                            .append("orderUpLoad", orderUpLoad);
                    break;
                }
            }
        }
        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public VtuzxMap getCollectionListYX(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String billNo = VtuzxUtil.getString(param, "billNo");
        String billNum = VtuzxUtil.getString(param, "billNum");
        String bankAccountName = VtuzxUtil.getString(param, "bankAccountName");//账户类型
        String settAccName = VtuzxUtil.getString(param, "settAccName");//账户名称
        String companyName = VtuzxUtil.getString(param, "companyName");//公司名称
        String shopName = VtuzxUtil.getString(param, "shopName");//销售渠道
        List<String> createTime = VtuzxUtil.getObject(param, "createTime");
        String createUsername = VtuzxUtil.getString(param, "createUserName");
        String tranName = VtuzxUtil.getString(param, "tranName");
        String isUpload = VtuzxUtil.getString(param, "isUpload");
        Criteria cond = new Criteria();
        //晓芹公司的
        cond.and("companyName").regex("野象");
        if (!VtuzxUtil.isEmpty(billNo)) {
            cond.and("billNo").regex(billNo);
        }
        if (!VtuzxUtil.isEmpty(bankAccountName)) {
            cond.and("bankAccountName").regex(bankAccountName);
        }
//        if(!VtuzxUtil.isEmpty(companyName)){
//            cond.and("companyName").regex(companyName);
//        }
        if (!VtuzxUtil.isEmpty(settAccName)) {
            cond.and("settAccName").regex(settAccName);
        }
        if (!VtuzxUtil.isEmpty(shopName)) {
            cond.and("shopName").regex(shopName);
        }
        if (!VtuzxUtil.isEmpty(billNum)) {
            cond.and("billNum").regex(billNum);
        }
        if (!VtuzxUtil.isEmpty(createUsername)) {
            cond.and("createUsername").regex(createUsername);
        }
        if (!VtuzxUtil.isEmpty(tranName)) {
            cond.and("tranName").regex(tranName);
        }
        if (!VtuzxUtil.isEmpty(isUpload)) {
            cond.and("isUpload").is(isUpload);
        }
        if (!VtuzxUtil.isEmpty(createTime)) {
            cond.and("createTime").gte(VtuzxUtil.parseDate(createTime.get(0))).lte(VtuzxUtil.parseDate(createTime.get(1) + " 23:59:59"));
        }

        VtuzxPage page = collectionDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("billNum", VtuzxUtil.getString(doc, "billNum"))//极客云单据号
                .append("billNo", VtuzxUtil.getString(doc, "billNo"))
                .append("companyName", VtuzxUtil.getString(doc, "companyName"))
                .append("createTime", VtuzxUtil.formatYmdHmsF(VtuzxUtil.getObject(doc, "createTime")))
                .append("createUserName", VtuzxUtil.getString(doc, "createUsername"))
                .append("tranName", VtuzxUtil.getString(doc, "tranName"))
                .append("isUpload", VtuzxUtil.getString(doc, "isUpload"))
                .append("unitName", VtuzxUtil.getString(doc, "unitName"))
                .append("bankAccountName", VtuzxUtil.getString(doc, "bankAccountName"))//账户类型
                .append("settAccName", VtuzxUtil.getString(doc, "settAccName"))//结算账户，（账户名称）
                .append("shopName", VtuzxUtil.getString(doc, "shopName"))//销售渠道
                .append("unitTypeName", VtuzxUtil.getString(doc, "unitTypeName"))
                .append("recInCuValue", VtuzxUtil.getInt(doc, "recInCuValue")));

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public VtuzxMap getPaymentListYX(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String billNo = VtuzxUtil.getString(param, "billNo");
        String billNum = VtuzxUtil.getString(param, "billNum");
        String bankAccountName = VtuzxUtil.getString(param, "bankAccountName");//账户类型
        String settAccName = VtuzxUtil.getString(param, "settAccName");//账户名称
        String companyName = VtuzxUtil.getString(param, "companyName");//账户名称
        String shopName = VtuzxUtil.getString(param, "shopName");//销售渠道
        List<String> createTime = VtuzxUtil.getObject(param, "createTime");
        String createUsername = VtuzxUtil.getString(param, "createUserName");
        String tranName = VtuzxUtil.getString(param, "tranName");
        String isUpload = VtuzxUtil.getString(param, "isUpload");
        Criteria cond = new Criteria();
        //晓芹公司的
        cond.and("companyName").regex("野象");
        if (!VtuzxUtil.isEmpty(billNo)) {
            cond.and("billNo").regex(billNo);
        }
        if (!VtuzxUtil.isEmpty(bankAccountName)) {
            cond.and("bankAccountName").regex(bankAccountName);
        }
//        if(!VtuzxUtil.isEmpty(companyName)){
//            cond.and("companyName").regex(companyName);
//        }
        if (!VtuzxUtil.isEmpty(settAccName)) {
            cond.and("settAccName").regex(settAccName);
        }
        if (!VtuzxUtil.isEmpty(shopName)) {
            cond.and("shopName").regex(shopName);
        }
        if (!VtuzxUtil.isEmpty(billNum)) {
            cond.and("billNum").regex(billNum);
        }
        if (!VtuzxUtil.isEmpty(createUsername)) {
            cond.and("createUsername").regex(createUsername);
        }
        if (!VtuzxUtil.isEmpty(tranName)) {
            cond.and("tranName").regex(tranName);
        }
        if (!VtuzxUtil.isEmpty(isUpload)) {
            cond.and("isUpload").is(isUpload);
        }
        if (!VtuzxUtil.isEmpty(createTime)) {
            cond.and("createTime").gte(VtuzxUtil.parseDate(createTime.get(0))).lte(VtuzxUtil.parseDate(createTime.get(1) + " 23:59:59"));
        }

        VtuzxPage page = paymentDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("billNum", VtuzxUtil.getString(doc, "billNum"))//极客云单据号
                .append("billNo", VtuzxUtil.getString(doc, "billNo"))
                .append("companyName", VtuzxUtil.getString(doc, "companyName"))
                .append("createTime", VtuzxUtil.formatYmdHmsF(VtuzxUtil.getObject(doc, "createTime")))
                .append("createUserName", VtuzxUtil.getString(doc, "createUsername"))
                .append("tranName", VtuzxUtil.getString(doc, "tranName"))
                .append("isUpload", VtuzxUtil.getString(doc, "isUpload"))
                .append("unitName", VtuzxUtil.getString(doc, "unitName"))
                .append("bankAccountName", VtuzxUtil.getString(doc, "bankAccountName"))//账户类型
                .append("settAccName", VtuzxUtil.getString(doc, "settAccName"))//结算账户，（账户名称）
                .append("shopName", VtuzxUtil.getString(doc, "shopName"))//销售渠道
                .append("unitTypeName", VtuzxUtil.getString(doc, "unitTypeName"))
                .append("recInCuValue", VtuzxUtil.getInt(doc, "recInCuValue")));

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public void uploadYexiangSaleBill(ObjectId userId, String name, File file, String orderTime) throws Exception {
        Date startTime = new Date();
        ObjectId objectId = startUpload(name, userId, startTime);
        List<VtuzxExcelSheet> sheets = VtuzxExcel.read(file);
        VtuzxExcelSheet sheet = sheets.get(0);
        int rowSize = sheet.rowSize();//多少行
        //避免单据过多,一次只传50条数据
        int count = rowSize / 50;//判断有多少个50条数据
        int remainder = rowSize % 50;//余数

        for (int size = 0; size < count; size++) {
            List<String> billNoList = new ArrayList<>();
            for (int i = size * 50; i < (size * 50) + 50; i++) {
                String billNo = "";
                int cellSize = sheet.row(i).cellSize();
                for (int ci = 0; ci < cellSize; ci++) {
                    if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }

            }
            //传金蝶单据
            uploadKingdeeSale(userId, name, billNoList, orderTime);
        }
        //处理一下余数部分
        if (remainder > 0) {
            List<String> billNoList = new ArrayList<>();
            for (int i = count * 50; i < rowSize; i++) {
                String billNo = "";
                int cellSize = sheet.row(i).cellSize();
                for (int ci = 0; ci < cellSize; ci++) {
                    if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }
            }
            //传金蝶单据
            uploadKingdeeSale(userId, name, billNoList, orderTime);
        }

        Date endDate = new Date();
        endUpload(name, userId, endDate, startTime, objectId);
    }

    @Override
    public void uploadYexiangInnersetteBill(ObjectId userId, String name, File file, String orderTime) throws Exception {
        Date startTime = new Date();
        ObjectId objectId = startUpload(name, userId, startTime);
        List<VtuzxExcelSheet> sheets = VtuzxExcel.read(file);
        VtuzxExcelSheet sheet = sheets.get(0);
        int rowSize = sheet.rowSize();//多少行
        //避免单据过多,一次只传50条数据
        int count = rowSize / 50;//判断有多少个50条数据
        int remainder = rowSize % 50;//余数

        for (int size = 0; size < count; size++) {
            List<String> billNoList = new ArrayList<>();
            for (int i = size * 50; i < (size * 50) + 50; i++) {
                String billNo = "";
                int cellSize = sheet.row(i).cellSize();
                for (int ci = 0; ci < cellSize; ci++) {
                    if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }

            }
            //传公司间调拨结算单道金蝶
            uploadKingdeeInnersettorder(userId, name, billNoList, orderTime);
        }
        //处理一下余数部分
        if (remainder > 0) {
            List<String> billNoList = new ArrayList<>();
            for (int i = count * 50; i < rowSize; i++) {
                String billNo = "";
                int cellSize = sheet.row(i).cellSize();
                for (int ci = 0; ci < cellSize; ci++) {
                    if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }
            }
            //传公司间调拨结算单道金蝶
            uploadKingdeeInnersettorder(userId, name, billNoList, orderTime);
        }

        Date endTime = new Date();
        endUpload(name, userId, endTime, startTime, objectId);
    }

    @Override
    public void uploadYexiangCollectionBill(ObjectId userId, String name, File file) throws Exception {
        Date startTime = new Date();
        ObjectId objectId = startUpload(name, userId, startTime);
        List<VtuzxExcelSheet> sheets = VtuzxExcel.read(file);
        VtuzxExcelSheet sheet = sheets.get(0);
        int rowSize = sheet.rowSize();//多少行
        //避免单据过多,一次只传50条数据
        int count = rowSize / 50;//判断有多少个50条数据
        int remainder = rowSize % 50;//余数

        for (int size = 0; size < count; size++) {
            List<String> billNoList = new ArrayList<>();
            for (int i = size * 50; i < (size * 50) + 50; i++) {
                String billNo = "";
                int cellSize = sheet.row(i).cellSize();
                for (int ci = 0; ci < cellSize; ci++) {
                    if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }

            }
            //传收款单到金蝶
            uploadKingdeeCollection(userId, name, billNoList);
        }
        //处理一下余数部分
        if (remainder > 0) {
            List<String> billNoList = new ArrayList<>();
            for (int i = count * 50; i < rowSize; i++) {
                String billNo = "";
                int cellSize = sheet.row(i).cellSize();
                for (int ci = 0; ci < cellSize; ci++) {
                    if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }
            }
            //传收款单到金蝶
            uploadKingdeeCollection(userId, name, billNoList);
        }

        Date endTime = new Date();
        endUpload(name, userId, endTime, startTime, objectId);

    }

    @Override
    public void uploadYexiangPaymentBill(ObjectId userId, String name, File file) throws Exception {
        List<VtuzxExcelSheet> sheets = VtuzxExcel.read(file);
        VtuzxExcelSheet sheet = sheets.get(0);
        int rowSize = sheet.rowSize();//多少行
        //避免单据过多,一次只传50条数据
        int count = rowSize / 50;//判断有多少个50条数据
        int remainder = rowSize % 50;//余数

        for (int size = 0; size < count; size++) {
            List<String> billNoList = new ArrayList<>();
            for (int i = size * 50; i < (size * 50) + 50; i++) {
                String billNo = "";
                int cellSize = sheet.row(i).cellSize();
                for (int ci = 0; ci < cellSize; ci++) {
                    if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }

            }
            //传付款单到金蝶
            uploadKingdeePayment(userId, billNoList);
        }
        //处理一下余数部分
        if (remainder > 0) {
            List<String> billNoList = new ArrayList<>();
            for (int i = count * 50; i < rowSize; i++) {
                String billNo = "";
                int cellSize = sheet.row(i).cellSize();
                for (int ci = 0; ci < cellSize; ci++) {
                    if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }
            }
            //传付款单到金蝶
            uploadKingdeePayment(userId, billNoList);
        }

    }

    /**
     * 导入excle传销售单(包含扣点信息)
     *
     * @param userId
     * @param name
     * @param file
     */
    @Override
    public void uploadYexiangSaleBillPoints(ObjectId userId, String name, File file, String orderTime) throws Exception {
        List<VtuzxExcelSheet> sheets = VtuzxExcel.read(file);
        VtuzxExcelSheet sheet = sheets.get(0);
        Date startTime = new Date();
        ObjectId objectId = startUpload(name, userId, startTime);
        int rowSize = sheet.rowSize();//多少行
        //避免单据过多,一次只传50条数据
        int count = rowSize / 50;//判断有多少个50条数据
        int remainder = rowSize % 50;//余数
        Map<String, Object> data = new HashMap<>();//key:销售单号 val:扣点信息
        for (int size = 0; size < count; size++) {
            List<String> billNoList = new ArrayList<>();//传销售出库单的
            List<String> orderNoList = new ArrayList<>();//传销售订单的
            for (int i = size * 50; i < (size * 50) + 50; i++) {
                String billNo = "";
                double points = 0;
                Double sign = 0.0;//标记
                if (sheet.row(i).cell(0).col() == 0) billNo = sheet.row(i).cell(0).strCellValue();
                //非空判断
                if (sheet.row(i).cell(1) != null) {
                    points = sheet.row(i).cell(1).doubleCellValue();
                }
                sheet.row(i);
                System.out.println(sheet.row(i));
                if (sheet.row(i).cell(2) != null) sign = sheet.row(i).cell(2).doubleCellValue();
                //TODO 暂时先0传销售出库单,1传销售订单
                if (0 != sign) {
                    if (!orderNoList.contains(billNo)) {
                        orderNoList.add(billNo);
                    }
                } else {
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }
                data.put(billNo, points);

            }
            //传金蝶销售出库单
            uploadKingdeeSalePonits(userId, name, billNoList, data, orderTime);
            //传金蝶销售订单
            if (!VtuzxUtil.isEmpty(orderNoList)) {
                uploadKingdeeSaleOrder(userId, name, orderNoList, data, orderTime);
            }
        }
        //处理一下余数部分
        if (remainder > 0) {
            List<String> billNoList = new ArrayList<>();
            List<String> orderNoList = new ArrayList<>();//传销售订单的
            for (int i = count * 50; i < rowSize; i++) {
                String billNo = "";
                double points = 0;
                double sign = 0;//标记
                if (sheet.row(i).cell(0).col() == 0) billNo = sheet.row(i).cell(0).strCellValue();
                //非空判断
                if (sheet.row(i).cell(1) != null) {
                    points = sheet.row(i).cell(1).doubleCellValue();
                }
                data.put(billNo, points);
                if (sheet.row(i).cell(2) != null) sign = sheet.row(i).cell(2).doubleCellValue();
                //TODO 暂时先0传销售出库单,1传销售订单
                if (0 != sign) {
                    if (!orderNoList.contains(billNo)) {
                        orderNoList.add(billNo);
                    }
                } else {
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }

            }
            //传金蝶单据
            uploadKingdeeSalePonits(userId, name, billNoList, data, orderTime);
            //传金蝶销售订单
            if (!VtuzxUtil.isEmpty(orderNoList)) {
                uploadKingdeeSaleOrder(userId, name, orderNoList, data, orderTime);
            }
        }

        Date endTime = new Date();
        endUpload(name, userId, endTime, startTime, objectId);

    }

    @Override
    public void uploadGuangnianOnline(ObjectId userId, String name, File file) throws Exception {
        List<VtuzxExcelSheet> sheets = VtuzxExcel.read(file);
        VtuzxExcelSheet sheet = sheets.get(0);
        int rowSize = sheet.rowSize();//多少行
        //避免单据过多,一次只传50条数据
        int count = rowSize / 50;//判断有多少个50条数据
        int remainder = rowSize % 50;//余数

        for (int size = 0; size < count; size++) {
            List<String> billNoList = new ArrayList<>();
            for (int i = size * 50; i < (size * 50) + 50; i++) {
                String billNo = "";
                int cellSize = sheet.row(i).cellSize();
                for (int ci = 0; ci < cellSize; ci++) {
                    if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }

            }
            //传金蝶单据(通过网店订单号传)
            uploadKingdeeSaleByOnline(userId, name, billNoList);
        }
        //处理一下余数部分
        if (remainder > 0) {
            List<String> billNoList = new ArrayList<>();
            for (int i = count * 50; i < rowSize; i++) {
                String billNo = "";
                int cellSize = sheet.row(i).cellSize();
                for (int ci = 0; ci < cellSize; ci++) {
                    if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                    if (!billNoList.contains(billNo)) {
                        billNoList.add(billNo);
                    }
                }
            }
            //传金蝶单据(通过网店订单号传)
            uploadKingdeeSaleByOnline(userId, name, billNoList);
        }


    }

    @Override
    public VtuzxMap getPriceList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String materialNo = VtuzxUtil.getString(param, "materialNo");
        Criteria cond = new Criteria();
        if (!VtuzxUtil.isEmpty(materialNo)) {
            cond.and("materialNo").regex(materialNo);
        }
        VtuzxPage page = priceListDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("materialNo", VtuzxUtil.getString(doc, "materialNo"))
                .append("materialName", VtuzxUtil.getString(doc, "materialName"))
                .append("specification", VtuzxUtil.getString(doc, "specification"))
                .append("unit", VtuzxUtil.getString(doc, "unit"))
                .append("createTime", VtuzxUtil.formatYmdHms(VtuzxUtil.getObject(doc, "createTime")))
                .append("currentPrice", VtuzxUtil.getDouble(doc, "currentPrice")));
        List<String> tradeNoList = new ArrayList<>();
        for (VtuzxMap data : dataList) {
            String trade = VtuzxUtil.getString(data, "tradeNo");
            tradeNoList.add(trade);
        }


        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public void syncPriceList(ObjectId userId, String name) throws Exception {
        //同步价目表之前先把之前同步的信息移到价目表日志集合中
        Iterator<Document> priceItr = priceListDao.findList(null, null, 0, 0);
        List<Document> priceList = new ArrayList<>();
        List<String> materialNoList = new ArrayList<>();
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            priceList.add(priceDoc);
            if (!materialNoList.contains(materialNo)) {
                materialNoList.add(materialNo);
            }
        }
        priceListLogDao.deleteMany(Criteria.where("materialNo").in(materialNoList));
        priceListLogDao.insertMany(priceList);
        priceListDao.deleteMany(Criteria.where("materialNo").in(materialNoList));

        basicService.syncPriceList(0, userId, name);

    }

    @Override
    public VtuzxMap getChannelList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String channelName = VtuzxUtil.getString(param, "channelName");
        //List<String> createTime = VtuzxUtil.getObject(param,"createTime");
        String warehouseName = VtuzxUtil.getString(param, "warehouseName");//

        Criteria cond = new Criteria();
        //晓芹公司的
        cond.and("companyName").regex("晓芹");
        if (!VtuzxUtil.isEmpty(channelName)) {
            cond.and("channelName").regex(channelName);
        }
        if (!VtuzxUtil.isEmpty(warehouseName)) {
            cond.and("warehouseName").regex(warehouseName);
        }

        VtuzxPage page = channelDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("channelName", VtuzxUtil.getString(doc, "channelName"))
                .append("companyName", VtuzxUtil.getString(doc, "companyName"))
                .append("warehouseCode", VtuzxUtil.getString(doc, "warehouseCode"))
                .append("createTime", VtuzxUtil.getString(doc, "createTime"))
                .append("warehouseName", VtuzxUtil.getString(doc, "warehouseName")));

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    /**
     * 同步渠道信息
     *
     * @param userId
     * @param name
     * @throws Exception
     */
    @Override
    public void syncChannelList(ObjectId userId, String name) throws Exception {
        basicService.syncChannel(null, null, 0);
    }

    /**
     * 同步仓库信息
     *
     * @param userId
     * @param name
     * @throws Exception
     */
    @Override
    public void syncWarehouseList(ObjectId userId, String name) throws Exception {
        basicService.syncWarehouse(null, null, 0);
    }

    /**
     * 根据出库单重传吉客云入库申请单
     *
     * @param goodsdocNo
     * @return
     */
    @Override
    public VtuzxMap syncStorageOut(String goodsdocNo) throws Exception {
        List<Document> storageList = new ArrayList<>();
        Document storageDoc = storageOutDao.findOne(Criteria.where("goodsdocNo").is(goodsdocNo));
        storageList.add(storageDoc);
        //获取token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        basicService.syncCreateStockIn(storageList, storeDoc);
        return null;
    }

    /**
     * 传金蝶吉客云销售单(包含扣点信息)
     *
     * @param userId
     * @param name
     * @param billNoList
     * @param tradeMap
     */
    private VtuzxMap uploadKingdeeSalePonits(ObjectId userId, String name, List<String> billNoList, Map<String, Object> tradeMap, String orderTime) throws Exception {

        Iterator<Document> saleOutItr = jikeyunSaleDao.findList(Criteria.where("tradeNo").in(billNoList), null, 0, 0);
        List<VtuzxMap> saleList = new ArrayList<>();
        while (saleOutItr.hasNext()) {
            Document allocationDoc = saleOutItr.next();

            String tradeNo = VtuzxUtil.getString(allocationDoc, "tradeNo");
//            Document innerSetterDoc = innersettorderDao.findOne(Criteria.where("sourceBillNo").is(tradeNo));
//            if (VtuzxUtil.isEmpty(innerSetterDoc)){
//                throw new VtuzxException(String.format("没有对应公司间结算单无法上传"));
//            }
//            String orderNo = VtuzxUtil.getString(innerSetterDoc,"orderNo");
//            String isUpload = VtuzxUtil.getString(innerSetterDoc,"isUpload");
//            if ("no".equals(isUpload)){
//                throw new VtuzxException(String.format("结算单号%s还没有上传，无法上传销售单",orderNo));
//            }
            VtuzxMap map = new VtuzxMap(allocationDoc);
            saleList.add(map);
        }

        VtuzxKingdeeCloudClient yeXiangClient = kingdeeService.loginKingdeeYeXiang();//野象

        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));

        for (VtuzxMap data : saleList) {
            String tradeNo = VtuzxUtil.getString(data, "tradeNo");
            String shopName = VtuzxUtil.getString(data, "shopName");//销售渠道
            String companyName = VtuzxUtil.getString(data, "companyName");//公司名称
            String flagNames = VtuzxUtil.getString(data, "flagNames");//标记名称
            double tradeCount = VtuzxUtil.getDouble(data, "tradeCount");
            Document historyDoc = syncOrderDao.findOne(Criteria.where("billNo").is(tradeNo));
            ObjectId id = null;
            if (historyDoc == null) {
                historyDoc = new Document("billNo", tradeNo);
            } else {
                id = VtuzxUtil.getObject(historyDoc, "_id");
            }
            historyDoc.append("billNo", tradeNo);
            historyDoc.append("userId", userId);
            historyDoc.append("userName", name);
            historyDoc.append("source", "source");
            historyDoc.append("data", data);
            historyDoc.append("event", "jackYunSaleOut");
            historyDoc.append("orderTime", orderTime);
            //判断是否是寄存单据,并且是商超的寄存订单第一次传金蝶销售订单，
            // 第二次再传就不传金蝶销售订单,判断有没有拆单,如果有拆单传销售出库单,没有的话就不传
            String success = "";//方法返回信息
            double points = (double) tradeMap.get(tradeNo);//扣点
            try {
                if (companyName.contains("百年晓芹")) {
                    if (tradeCount >= 0) { //销售出
                        String cond = String.format("F_PSUH_XSDH = '%s'", tradeNo);
                        List<VtuzxMap> saleOrder = kingdeeService.query(yeXiangClient, "SAL_OUTSTOCK", new VtuzxArrayList<>(
                                "FBillNo"//单据编号
                        ), cond);
                        //说明已经传过,跳过当前循环
                        if (saleOrder != null && saleOrder.size() > 0) {
                            continue;
                        }
                        success = syncKingdeeSaleOutOnePoints(yeXiangClient, data, historyDoc, storeDoc, points);
                    } else {//负数传野象销售退
                        String cond = String.format("F_PSUH_XSDH = '%s'", tradeNo);
                        List<VtuzxMap> saleOrder = kingdeeService.query(yeXiangClient, "SAL_RETURNSTOCK", new VtuzxArrayList<>(
                                "FBillNo"//单据编号
                        ), cond);
                        //说明已经传过,跳过当前循环
                        if (saleOrder != null && saleOrder.size() > 0) {
                            continue;
                        }
                        success = syncKingdeeSaleReturnYXPonits(yeXiangClient, data, historyDoc, points);
                    }
                }

                //如果返回值有信息说明是错误的
                if (!VtuzxUtil.isEmpty(success)) {
                    historyDoc.append("success", false);
                    if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {

                        historyDoc.append("updateUserId", userId);
                        historyDoc.append("success", false);
                        historyDoc.append("updateUserName", name);
                        syncOrderDao.updateById(id, historyDoc);
                    }
                    String _id = VtuzxUtil.getString(data, "_id");
                    jikeyunSaleDao.updateById(_id, new Document("isUpload", "no"));
                } else {
                    historyDoc.append("success", true);
                    if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {
                        historyDoc.remove("_id");
                        historyDoc.remove("createTime");
                        historyDoc.remove("updateTime");
                        //不知道为啥remove删除字段后还有信息
                        historyDoc.append("message", "");
                        historyDoc.append("updateUserId", userId);
                        historyDoc.append("updateUserName", name);
                        syncOrderDao.updateById(id, historyDoc);
                    }
                    String _id = VtuzxUtil.getString(data, "_id");
                    jikeyunSaleDao.updateById(_id, new Document("isUpload", "yes"));
                }

            } catch (Exception e) {
                //因为物料编码原因没传成功的给与提示
                if (e.getMessage().contains("物料编码")) {
                    historyDoc.append("prdInStockStock", false).append("message", e.getMessage() + "请到中台同步物料").append("success", false);
                } else if (e.getMessage().contains("仓库")) {
                    historyDoc.append("prdInStockStock", false).append("message", "金蝶没有对应仓库,请维护").append("success", false);
                } else {
                    historyDoc.append("prdInStockStock", false).append("message", e.getMessage()).append("success", false);
                }

                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    syncOrderDao.updateById(id, historyDoc);
                }
                _logger.info(e.getMessage());
//                throw new VtuzxException(e.getMessage());
            }

        }

        return null;
    }

    /**
     * 传金蝶销售订单
     *
     * @param userId
     * @param name
     * @param billNoList
     * @param tradeMap
     */
    private VtuzxMap uploadKingdeeSaleOrder(ObjectId userId, String name, List<String> billNoList, Map<String, Object> tradeMap, String orderTime) throws Exception {

        Iterator<Document> saleOrderItr = jikeyunSaleDao.findList(Criteria.where("tradeNo").in(billNoList), null, 0, 0);
        List<VtuzxMap> saleList = new ArrayList<>();
        while (saleOrderItr.hasNext()) {
            Document allocationDoc = saleOrderItr.next();
            VtuzxMap map = new VtuzxMap(allocationDoc);
            saleList.add(map);
        }

        VtuzxKingdeeCloudClient yeXiangClient = kingdeeService.loginKingdeeYeXiang();//野象

        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));

        for (VtuzxMap data : saleList) {
            String tradeNo = VtuzxUtil.getString(data, "tradeNo");
            String shopName = VtuzxUtil.getString(data, "shopName");//销售渠道
            String companyName = VtuzxUtil.getString(data, "companyName");//公司名称
            String flagNames = VtuzxUtil.getString(data, "flagNames");//标记名称
            double tradeCount = VtuzxUtil.getDouble(data, "tradeCount");
            Document historyDoc = syncOrderDao.findOne(Criteria.where("billNo").is(tradeNo));
            ObjectId id = null;
            if (historyDoc == null) {
                historyDoc = new Document("billNo", tradeNo);
            } else {
                id = VtuzxUtil.getObject(historyDoc, "_id");
            }
            historyDoc.append("billNo", tradeNo);
            historyDoc.append("userId", userId);
            historyDoc.append("userName", name);
            historyDoc.append("source", "source");
            historyDoc.append("data", data);
            historyDoc.append("event", "jackYunSaleOut");
            historyDoc.append("orderTime", orderTime);
            String success = "";//方法返回信息
            double points = (double) tradeMap.get(tradeNo);//扣点
            try {
                //判断是否是寄存的单据
                if (!flagNames.contains("寄存")) {
                    //不是寄存的直接跳过
                    continue;
                }
                if (companyName.contains("百年晓芹")) {
                    String cond = String.format("F_PSUH_XSDH = '%s'", tradeNo);
                    List<VtuzxMap> saleOrder = kingdeeService.query(yeXiangClient, "SAL_SaleOrder", new VtuzxArrayList<>(
                            "FBillNo"//单据编号
                    ), cond);
                    //说明已经传过,跳过当前循环
                    if (saleOrder != null && saleOrder.size() > 0) {
                        continue;
                    }

                    success = syncKingdeeSaleOrderYxPoints(yeXiangClient, data, historyDoc, storeDoc, points);

                }
                //如果返回值有信息说明是错误的
                if (!VtuzxUtil.isEmpty(success)) {
                    historyDoc.append("success", false);
                    if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {

                        historyDoc.append("updateUserId", userId);
                        historyDoc.append("success", false);
                        historyDoc.append("updateUserName", name);
                        syncOrderDao.updateById(id, historyDoc);
                    }
                    String _id = VtuzxUtil.getString(data, "_id");
                    jikeyunSaleDao.updateById(_id, new Document("isUpload", "no"));
                } else {
                    historyDoc.append("success", true);
                    if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {
                        historyDoc.remove("_id");
                        historyDoc.remove("createTime");
                        historyDoc.remove("updateTime");
                        //不知道为啥remove删除字段后还有信息
                        historyDoc.append("message", "");
                        historyDoc.append("updateUserId", userId);
                        historyDoc.append("updateUserName", name);
                        syncOrderDao.updateById(id, historyDoc);
                    }
                    String _id = VtuzxUtil.getString(data, "_id");
                    jikeyunSaleDao.updateById(_id, new Document("isUpload", "yes"));
                }

            } catch (Exception e) {
                //因为物料编码原因没传成功的给与提示
                if (e.getMessage().contains("物料编码")) {
                    historyDoc.append("prdInStockStock", false).append("message", e.getMessage() + "请到中台同步物料").append("success", false);
                } else if (e.getMessage().contains("仓库")) {
                    historyDoc.append("prdInStockStock", false).append("message", "金蝶没有对应仓库,请维护").append("success", false);
                } else {
                    historyDoc.append("prdInStockStock", false).append("message", e.getMessage()).append("success", false);
                }

                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    syncOrderDao.updateById(id, historyDoc);
                }

                _logger.info(e.getMessage());
//                throw new VtuzxException(e.getMessage());

            }

        }

        return null;
    }

    /**
     * 野象销售订单(带税点)
     *
     * @param yeXiangClient
     * @param data
     * @param historyDoc
     * @param storeDoc
     * @param points
     * @return
     */
    private String syncKingdeeSaleOrderYxPoints(VtuzxKingdeeCloudClient yeXiangClient, VtuzxMap data, Document historyDoc, Document storeDoc, double points) throws Exception {
        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data, "customerName");//客户名称
        String orderTime = VtuzxUtil.getString(historyDoc, "orderTime");//单据如期
        String seller = VtuzxUtil.getString(data, "seller");//业务员
        String departName = VtuzxUtil.getString(data, "departName");//部门
        if (VtuzxUtil.isEmpty(customerName)) {
            historyDoc.append("message", "吉客云销售单还未结算请先结算");
            return "吉客云销售单还未结算请先结算";
        }
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");
        String shopName = VtuzxUtil.getString(data, "shopName");//店铺名称
        //String customerId = getCustomer(customerCode, yeXiangClient, storeDoc,customerName);//获取到传金蝶的客户编号

        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        if (VtuzxUtil.isEmpty(channelDoc)) {
            historyDoc.append("message", "无法查询到渠道,请维护渠道");
            return "无法查询到渠道,请维护渠道";
        }

        if (!VtuzxUtil.isEmpty(seller)) {
            //如果部门没同步下来的话
            if (VtuzxUtil.isEmpty(departName)) {
                departName = getMainDepartName(seller, storeDoc);//吉客云部门名称
            }
        }
        String deliveryDeptId = "";//发货部门id
        if (!VtuzxUtil.isEmpty(departName)) {//如果吉客云部门名称不为空，查询金蝶部门id
            //查询发货部门id
            String cond = String.format("FName = '%s' and FForbidStatus ='%s'", departName, "A");
            List<VtuzxMap> bd_department = kingdeeService.query(yeXiangClient, "BD_Department", new VtuzxArrayList<>(
                    "FNumber",//=部门编码
                    "FNAME"//部门
            ), cond);
            if (bd_department != null && bd_department.size() > 0) {//如果有这个客户的话
                deliveryDeptId = (String) bd_department.get(0).get("FNumber");
            }
        }
        //如果发货部门为空的话不让传
        if (VtuzxUtil.isEmpty(deliveryDeptId)) {
            historyDoc.append("message", "无法查询到部门,请维护");
            return "无法查询到部门,请维护";
        }

        String customerId = getCustomerShopName(yeXiangClient, shopName);

        //如果金蝶没有这个客户的haul
        if (VtuzxUtil.isEmpty(customerId)) {
            historyDoc.append("message", "无法查询到客户,请维护");
            return "无法查询到客户,请维护";
        }
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        Map<String, Object> model = new LinkedHashMap<>();//金蝶销售订单model
        model.put("Fid", 0);
        model.put("FDate", orderTime);
        model.put("FBillTypeID", new Document("FNumber", "XSDD01_SYS"));
        model.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        //客户传销售渠道
        model.put("FCustId", new Document("FNumber", customerId));//客户
        model.put("FSaleDeptId", new Document("FNumber", deliveryDeptId));//销售部门
//        model.put("FSettleId",new Document("FNumber","04.01.003"));//结算方
//        model.put("FChargeId",new Document("FNumber","04.01.003"));//付款方
        model.put("F_PSUH_SFJC", "1");//是否寄存
        model.put("F_PSUH_jikeyunbiaoji", tradeNo);//吉客云标记暂时传吉客云销售单号
        model.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
        model.put("F_PSUH_XSQD", channelGroup);//销售渠道
        model.put("F_PSUH_DPMC", shopName);//店铺名称
        model.put("F_PSUH_KD", points);//扣点
        model.put("F_PSUH_KHMC", customerName);//客户名称
        Map<String, Object> orderFinance = new LinkedHashMap<>();//财务信息参数
        orderFinance.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        orderFinance.put("FIsPriceExcludeTax ", true);//价外税
        orderFinance.put("FIsIncludedTax ", true);//是否含税
        model.put("FSaleOrderFinance", orderFinance);
        List<Map<String, Object>> orderEntity = new ArrayList<>();//物料信息
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");//货品信息
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        //循环货品集合，添加金蝶单据体信息
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        //循环货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "ShareFavourableAfterFee");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        String cond = String.format("Fname = '%s'", unitName);
                        List<VtuzxMap> bd_customer = kingdeeService.query(yeXiangClient, "BD_UNIT", new VtuzxArrayList<>(
                                "FNumber",//物料编码
                                "FNAME"//物料名称
                        ), cond);
                        //获取物料编码
                        String unit = "";
                        if (bd_customer != null && bd_customer.size() > 0) {
                            unit = bd_customer.get(0).getString("FNumber");
                        }

                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//单位
                        colMap.put("FPriceUnitId", new Document("FNumber", unit));//计价单位
                        colMap.put("FTaxPrice", new BigDecimal(settPrice * (1 - points) / skuCount)
                                .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//单价
                        colMap.put("FPriceUnitQty", skuCount);//计价数量
                        colMap.put("FSettleOrgIds", new Document("FNumber", "100"));//结算组织
                        orderEntity.add(colMap);
                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee");//分摊后金额,对应金蝶含税单价
                double skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(yeXiangClient, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",//物料编码
                        "FNAME"//物料名称
                ), cond);
                //获取物料编码
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }

                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//单位
                colMap.put("FPriceUnitId", new Document("FNumber", unit));//计价单位
                colMap.put("FTaxPrice", new BigDecimal(settPrice * (1 - points) / skuCount)
                        .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//单价
                colMap.put("FPriceUnitQty", skuCount);//计价数量
                colMap.put("FSettleOrgIds", new Document("FNumber", "100"));//结算组织
                orderEntity.add(colMap);
            }


        }

        model.put("FSaleOrderEntry", orderEntity);

        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", true);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", model);

        historyDoc.append("param", model);
        //创建销售订单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(yeXiangClient, "SAL_SaleOrder", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(yeXiangClient, "SAL_SaleOrder", "0", number);
            kingdeeService.audit(yeXiangClient, "SAL_SaleOrder", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            throw new VtuzxException(e.getMessage());
        }
        return "";
    }

    /**
     * 野象销售退(带扣点的)
     *
     * @param client
     * @param data
     * @param historyDoc
     * @param points
     */
    private String syncKingdeeSaleReturnYXPonits(VtuzxKingdeeCloudClient client, VtuzxMap data, Document historyDoc, double points) throws Exception {
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data, "customerName");//客户名称
        String orderTime = VtuzxUtil.getString(historyDoc, "orderTime");//单据日期
        //如果名称为空的话说明是没有结算单给与提示
        if (VtuzxUtil.isEmpty(customerName)) {
            historyDoc.append("message", "当前订单没有生成结算销售单,请生成结算销售单后在上传");
            return "当前订单没有生成结算销售单,请生成结算销售单后在上传";
        }
        String customerId = getCustomer(customerCode, client, storeDoc, customerName);
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号
        String shopName = VtuzxUtil.getString(data, "shopName");//店铺名称
        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        //如果查询不到销售渠道
        if (VtuzxUtil.isEmpty(channelDoc)) {
            historyDoc.append("message", "无法查询到销售渠道,请维护渠道");
            return "无法查询到销售渠道,请维护渠道";
        }
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息

        String seller = VtuzxUtil.getString(data, "seller");//业务员
        String createTime = VtuzxUtil.getString(data, "gmtCreate");//创建日期
        String warehouseName = VtuzxUtil.getString(data, "warehouseName");//仓库对应销售渠道


        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型 标准销售退货单
        payModel.put("FDate", orderTime);//单据日期
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        payModel.put("FRetcustId", new Document("FNumber", customerId));//退货客户
        payModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        payModel.put("FStockOrgId", new Document("FNumber", "100"));//库存组织
        payModel.put("FReceiveCustId", new Document("FNumber", customerId));//收货方
        payModel.put("FSettleCustId", new Document("FNumber", customerId));//结算方
        payModel.put("FPayCustId", new Document("FNumber", customerId));//付款方
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务标识
        payModel.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
        payModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        payModel.put("F_PSUH_DPMC", shopName);//店铺名称
        payModel.put("F_PSUH_KD", points);//扣点
        payModel.put("F_PSUH_KHMC", customerName);//客户名称
        payModel.put("F_SXLJ_JKYKHBH", customerCode);//客户编号
        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率

        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        List<String> materialNoList = new ArrayList<>();
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            //存在零税率的增值税
            String substring = "";
            if (fTaxRateName.indexOf("%") > 0) {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            } else {
                substring = "0";
            }

            taxMap.put(materialNo, Double.parseDouble(substring));
        }
        //循环整理后的货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "ShareFavourableAfterFee");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        skuCount = Math.abs(skuCount);
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        String cond = String.format("Fname = '%s'", unitName);
                        List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                                "FNumber",//物料编码
                                "FNAME"//物料名称
                        ), cond);
                        //获取物料编码
                        String unit = "";
                        if (bd_customer != null && bd_customer.size() > 0) {
                            unit = bd_customer.get(0).getString("FNumber");
                        }
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");//产品类型
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", skuCount);//实退数量
                        colMap.put("FTaxPrice", new BigDecimal(settPrice * (1 - points) / skuCount)
                                .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//含税单价
                        if (isGift == 1) {//是赠品
                            colMap.put("isFree", true);
                        } else {
                            colMap.put("isFree", false);
                        }
                        colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                        colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                        colMap.put("FOwnerId", new Document("FNumber", "100"));//货主开发销售测试
                        colMap.put("FStockId", new Document("FNumber", "XQ03"));//仓库售后退货仓
                        colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态

                        colMap.put("FDeliveryDate", createTime);//退货日期
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSalUnitQty", skuCount);//销售数量
                        colMap.put("FSalBaseQty", skuCount);//销售基本数量
                        colMap.put("FPriceBaseQty", skuCount);//计价基本数量
                        //获取税率信息
                        double tax = (double) taxMap.get(goodsNo);
                        colMap.put("FEntryTaxRate", tax);//税率
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
                        colMap.put("FIsReturnCheck", false);//发货检验
                        colMap.put("FNote ", goodsMemo);//货品备注
                        FEntity.add(colMap);
                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee");//分摊后金额,对应金蝶含税单价
                double skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                skuCount = Math.abs(skuCount);
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",//物料编码
                        "FNAME"//物料名称
                ), cond);
                //获取物料编码
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }
                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");//产品类型
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", skuCount);//实退数量
                colMap.put("FTaxPrice", new BigDecimal(settPrice * (1 - points) / skuCount)
                        .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//含税单价
                if (isGift == 1) {//是赠品
                    colMap.put("isFree", true);
                } else {
                    colMap.put("isFree", false);
                }
                colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                colMap.put("FOwnerId", new Document("FNumber", "100"));//货主开发销售测试
                colMap.put("FStockId", new Document("FNumber", "XQ03"));//仓库售后退货仓
                colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态

                colMap.put("FDeliveryDate", createTime);//退货日期
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSalUnitQty", skuCount);//销售数量
                colMap.put("FSalBaseQty", skuCount);//销售基本数量
                colMap.put("FPriceBaseQty", skuCount);//计价基本数量
                //获取税率信息
                double tax = (double) taxMap.get(goodsNo);
                colMap.put("FEntryTaxRate", tax);//税率
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
                colMap.put("FIsReturnCheck", false);//发货检验
                colMap.put("FNote ", goodsMemo);//货品备注
                FEntity.add(colMap);
            }


        }
        //循环货品集合，添加金蝶单据体信息

        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        historyDoc.append("param", payModel);
        //创建销售退货单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {

            if (e.getMessage().contains("货主组织已关账")) {
                //如果是因为关账原因没有上传成功的需要重新上传,日期为下个月的第一天
                String closeTime = e.getMessage().substring(48, 58);
                Date closeDate = VtuzxUtil.parseDate(closeTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(closeDate);
                calendar.add(Calendar.MONTH, 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);//当月第一天
                Date time = calendar.getTime();
                String firstTime = VtuzxUtil.formatYmdHmsF(time);
                syncKingdeeSaleReturnYXPonitsAccount(client, data, historyDoc, storeDoc, firstTime, points);
            } else {
                _logger.info(tradeNo + e.getMessage());
                throw new VtuzxException(e.getMessage());
            }
        }
        return "";
    }

    /**
     * 野象销售退(扣点)因为关账日期原因
     *
     * @param client
     * @param data
     * @param historyDoc
     * @param storeDoc
     * @param firstTime
     * @param points
     */
    private String syncKingdeeSaleReturnYXPonitsAccount(VtuzxKingdeeCloudClient client, VtuzxMap data, Document historyDoc, Document storeDoc, String firstTime, double points) throws Exception {

        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data, "customerName");//客户名称
        //如果名称为空的话说明是没有结算单给与提示
        if (VtuzxUtil.isEmpty(customerName)) {
            historyDoc.append("message", "当前订单没有生成结算销售单,请生成结算销售单后在上传");
            return "当前订单没有生成结算销售单,请生成结算销售单后在上传";
        }
        String customerId = getCustomer(customerCode, client, storeDoc, customerName);
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号
        String shopName = VtuzxUtil.getString(data, "shopName");//店铺名称
        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        //如果查询不到销售渠道
        if (VtuzxUtil.isEmpty(channelDoc)) {
            historyDoc.append("message", "无法查询到销售渠道,请维护渠道");
            return "无法查询到销售渠道,请维护渠道";
        }
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息

        String seller = VtuzxUtil.getString(data, "seller");//业务员
        String createTime = VtuzxUtil.getString(data, "gmtCreate");//创建日期
        String warehouseName = VtuzxUtil.getString(data, "warehouseName");//仓库对应销售渠道


        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型 标准销售退货单
        payModel.put("FDate", firstTime);//单据日期
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        payModel.put("FRetcustId", new Document("FNumber", customerId));//退货客户
        payModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        payModel.put("FStockOrgId", new Document("FNumber", "100"));//库存组织
        payModel.put("FReceiveCustId", new Document("FNumber", customerId));//收货方
        payModel.put("FSettleCustId", new Document("FNumber", customerId));//结算方
        payModel.put("FPayCustId", new Document("FNumber", customerId));//付款方
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务标识
        payModel.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
        payModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        payModel.put("F_PSUH_DPMC", shopName);//店铺名称
        payModel.put("F_PSUH_KD", points);//扣点
        payModel.put("F_PSUH_KHMC", customerName);//客户名称
        payModel.put("F_SXLJ_JKYKHBH", customerCode);//客户编号
        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率

        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        List<String> materialNoList = new ArrayList<>();
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }

            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //循环整理后的货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "ShareFavourableAfterFee");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        skuCount = Math.abs(skuCount);
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        String unit = (String) unitMap.get(unitName);
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");//产品类型
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", skuCount);//实退数量
                        colMap.put("FTaxPrice", new BigDecimal(settPrice * (1 - points) / skuCount)
                                .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//含税单价
                        if (isGift == 1) {//是赠品
                            colMap.put("isFree", true);
                        } else {
                            colMap.put("isFree", false);
                        }
                        colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                        colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                        colMap.put("FOwnerId", new Document("FNumber", "100"));//货主开发销售测试
                        colMap.put("FStockId", new Document("FNumber", "XQ03"));//仓库售后退货仓
                        colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态

                        colMap.put("FDeliveryDate", createTime);//退货日期
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSalUnitQty", skuCount);//销售数量
                        colMap.put("FSalBaseQty", skuCount);//销售基本数量
                        colMap.put("FPriceBaseQty", skuCount);//计价基本数量
                        //获取税率信息
                        double tax = (double) taxMap.get(goodsNo);
                        colMap.put("FEntryTaxRate", tax);//税率
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
                        colMap.put("FIsReturnCheck", false);//发货检验
                        colMap.put("FNote ", goodsMemo);//货品备注
                        FEntity.add(colMap);
                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee");//分摊后金额,对应金蝶含税单价
                double skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                skuCount = Math.abs(skuCount);
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String unit = (String) unitMap.get(unitName);
                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");//产品类型
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", skuCount);//实退数量
                colMap.put("FTaxPrice", new BigDecimal(settPrice * (1 - points) / skuCount)
                        .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//含税单价
                if (isGift == 1) {//是赠品
                    colMap.put("isFree", true);
                } else {
                    colMap.put("isFree", false);
                }
                colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                colMap.put("FOwnerId", new Document("FNumber", "100"));//货主开发销售测试
                colMap.put("FStockId", new Document("FNumber", "XQ03"));//仓库售后退货仓
                colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态

                colMap.put("FDeliveryDate", createTime);//退货日期
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSalUnitQty", skuCount);//销售数量
                colMap.put("FSalBaseQty", skuCount);//销售基本数量
                colMap.put("FPriceBaseQty", skuCount);//计价基本数量
                //获取税率信息
                double tax = (double) taxMap.get(goodsNo);
                colMap.put("FEntryTaxRate", tax);//税率
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
                colMap.put("FIsReturnCheck", false);//发货检验
                colMap.put("FNote ", goodsMemo);//货品备注
                FEntity.add(colMap);
            }


        }
        //循环货品集合，添加金蝶单据体信息

        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        historyDoc.append("param", payModel);
        //创建销售退货单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {

            throw new VtuzxException(e.getMessage());

        }
        return "";
    }

    /**
     * 野象销售出(带扣点)
     *
     * @param client
     * @param data
     * @param historyDoc
     * @param storeDoc
     * @param points
     * @return
     */
    private String syncKingdeeSaleOutOnePoints(VtuzxKingdeeCloudClient client, VtuzxMap data, Document historyDoc, Document storeDoc, double points) throws Exception {
        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data, "customerName");//客户名称
        String orderTime = VtuzxUtil.getString(historyDoc, "orderTime");//单据日期
        //如果名称为空的话说明是没有结算单给与提示
        if (VtuzxUtil.isEmpty(customerName)) {
            historyDoc.append("message", "当前订单没有生成结算销售单,请生成结算销售单后在上传");
            return "当前订单没有生成结算销售单,请生成结算销售单后在上传";
        }
        String customerId = getCustomer(customerCode, client, storeDoc, customerName);
        String warehouseName = VtuzxUtil.getString(data, "warehouseName");//仓库名称(吉客云销售渠道)
        String shopName = VtuzxUtil.getString(data, "shopName");//店铺名称
        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        //如果查询不到销售渠道
        if (VtuzxUtil.isEmpty(channelDoc)) {
            historyDoc.append("message", "无法查询到销售渠道,请维护渠道");
            return "无法查询到销售渠道,请维护渠道";
        }
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号

        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        double otherFee = VtuzxUtil.getDouble(data, "otherFee");//销售费用
        double discountFee = VtuzxUtil.getDouble(data, "discountFee");//整单优惠
        double couponFee = VtuzxUtil.getDouble(data, "couponFee");//平台补贴(平台优惠)
        String sellerMemo = VtuzxUtil.getString(data, "sellerMemo");//备注(客服备注)
        String buyerMemo = VtuzxUtil.getString(data, "buyerMemo");//(买家备注)客户备注
        String appendMemo = VtuzxUtil.getString(data, "appendMemo");//追加备注
        String onlineTradeNo = VtuzxUtil.getString(data, "onlineTradeNo");//网店订单号
        String seller = VtuzxUtil.getString(data, "seller");//业务员
        String flagNames = VtuzxUtil.getString(data, "flagNames");//标记名称
        String createTime = VtuzxUtil.getString(data, "gmtCreate");//创建日期
//        Date consignTime = VtuzxUtil.getObject(data,"consignTime");//发货日期
        String tradeTime = VtuzxUtil.getString(data, "tradeTime");//下单时间
        String departName = VtuzxUtil.getString(data, "departName");//部门名称
        String invoiceStatus = VtuzxUtil.getString(data, "invoiceStatus");//是否开票
        String endTime = "";
        if (!VtuzxUtil.isEmpty(createTime)) {
            Date createDate = VtuzxUtil.parseDate(createTime);
            Calendar right = Calendar.getInstance();
            right.setTime(createDate);
            right.add(Calendar.MONTH, 1);
            Date endDate = right.getTime();
            endTime = VtuzxUtil.formatYmdHmsF(endDate);
        }

        String salesManId = "";
        if (!VtuzxUtil.isEmpty(seller)) {
            //如果部门没同步下来的话
            if (VtuzxUtil.isEmpty(departName)) {
                departName = getMainDepartName(seller, storeDoc);//吉客云部门名称
            }
            salesManId = getSellId(seller, client);//金蝶业务员id
        }

        String deliveryDeptId = "";//发货部门id
        if (!VtuzxUtil.isEmpty(departName)) {//如果吉客云部门名称不为空，查询金蝶部门id
            //查询发货部门id
            String cond = String.format("FName = '%s' and FForbidStatus ='%s'", departName, "A");
            List<VtuzxMap> bd_department = kingdeeService.query(client, "BD_Department", new VtuzxArrayList<>(
                    "FNumber",//=部门编码
                    "FNAME"//部门
            ), cond);
            if (bd_department != null && bd_department.size() > 0) {//如果有这个客户的话
                deliveryDeptId = (String) bd_department.get(0).get("FNumber");
            }
        }
        //如果发货部门为空的话不让传
        if (VtuzxUtil.isEmpty(deliveryDeptId)) {
            historyDoc.append("message", "无法查询到部门,请维护");
            return "无法查询到部门,请维护";
        }

        //在同步单据的时候会查询仓库id
        //存在没有仓库的情况,给与提示
        String stockId = VtuzxUtil.getString(data, "stockId");
        if (VtuzxUtil.isEmpty(stockId)) {
            historyDoc.append("message", "没有获取到仓库id,请重新同步单据");
            return "没有获取到仓库id,请重新同步单据";
        }
        //查询客户(门店通过部门查询客户，其他的通过渠道查询)
        String shopCustomerId = "";
        if (shopName.startsWith("bb")) {
            shopCustomerId = getCustomerShopName(client, departName);
        } else {
            //添加门店渠道中的对应关系
            if ("野象考拉店铺".equals(shopName)) {
                shopName = "网易考拉";
            } else if ("野象苏宁超市".equals(shopName)) {
                shopName = "苏宁超市";
            } else if ("客服外卖-代收货款".equals(shopName)) {
                shopName = "客服外卖";
            } else if ("野象-展示厅".equals(shopName)) {
                shopName = "展示厅";
            }
            shopCustomerId = getCustomerShopName(client, shopName);
        }

        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSCKD01_SYS"));//单据类型 标准销售出库单
        if (!VtuzxUtil.isEmpty(orderTime)) {
            payModel.put("FDate", orderTime);//单据日期
        } else {
            payModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));//单据日期
        }
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        //如果是外埠的客户还是正常客户
        if ("外埠".equals(channelGroup)) {
            payModel.put("FCustomerID", new Document("FNumber", customerId));//客户
        } else {//其他的传渠道信息
            payModel.put("FCustomerID", new Document("FNumber", shopCustomerId));//渠道
        }
        payModel.put("FSalesManID", new Document("FNumber", salesManId));//销售员
        payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织
        payModel.put("FDeliveryDeptID", new Document("FNumber", deliveryDeptId));//发货部门
        payModel.put("FSaleDeptID", new Document("FNumber", deliveryDeptId));//销售部门

        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务或费用
        payModel.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
        payModel.put("F_ora_disFee", discountFee);//整单优惠
        payModel.put("F_ora_appendMemo", appendMemo);//追加备注
        payModel.put("F_ora_saleFee", otherFee);//销售费用
//        payModel.put("F_ora_kefuMemo",sellerMemo);//客服备注
        payModel.put("F_ora_kehuMemo", buyerMemo);//客户备注
        payModel.put("F_ora_lineTradeNo", onlineTradeNo);//网店单号
        payModel.put("F_PSUH_biaoji", flagNames);//标记
        payModel.put("F_PSUH_couponFee", couponFee);//平台补贴
        payModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        payModel.put("F_PSUH_DPMC", shopName);//店铺名称
        payModel.put("F_PSUH_KD", points);//扣点
        payModel.put("F_PSUH_XDSJ", tradeTime);//下单时间
        payModel.put("F_SXLJ_JKYKHBH", customerCode);//客户编号
        //如果是3的话为开票成功，其他为未开票
        if ("3".equals(invoiceStatus)) {
            payModel.put("F_PSUH_SFKP", true);//是否开票
        } else {
            payModel.put("F_PSUH_SFKP", false);//是否开票
        }

        //如果是寄存的单据,下单时间和创建时间在同月是正常销售单,不是同月的加一个寄存标记(为了不用算钱)
        if (flagNames.contains("寄存")) {
            if (!VtuzxUtil.isEmpty(tradeTime)) {
                String createSub = createTime.substring(5, 7);//创建日期月份
                String tradeSub = tradeTime.substring(5, 7);//下单日期月份
                if (!createSub.equals(tradeSub)) {
                    payModel.put("F_PSUH_JCBJ", "寄存");//寄存标记
                }
            }
        }

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FIsIncludedTax", true);//是否含税
        SubHeadEntity.put("FLocalCurrID", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        SubHeadEntity.put("FIsPriceExcludeTax", true);//价外税
        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        //循环货品集合，添加金蝶单据体信息
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }

            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //查询价目表获取标准成本价
        Map<String, Object> priceMap = new HashMap<>();//key:物料编码 value : 标准成本
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            double standardPrice = VtuzxUtil.getDouble(priceDoc, "standardPrice");
            priceMap.put(materialNo, standardPrice);
        }
        //添加单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "ShareFavourableAfterFee");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        //查询单位编码，直接传文字无效
                        String unit = (String) unitMap.get(unitName);
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        //金蝶单价为0就是赠品
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", skuCount);//实发数量
                        //含税单价需要口减掉扣点
                        colMap.put("FTaxPrice", new BigDecimal(settPrice * (1 - points) / skuCount)
                                .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//含税单价
                        //单价是0就是赠品
                        if (settPrice == 0) {
                            colMap.put("FIsFree", true);//是否赠品
                        } else {
                            colMap.put("FIsFree", false);//是否赠品
                        }

                        colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                        colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                        double tax = (Double) taxMap.get(goodsNo);//获取税率
                        colMap.put("FEntryTaxRate", tax);//税率
                        colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                        colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                        colMap.put("FEntroynote", goodsMemo);//货品备注
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSALUNITQTY", skuCount);//销售数量
                        colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                        colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                        colMap.put("FOUTCONTROL", false);//控制出库数量
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                        colMap.put("FCheckDelivery", false);//发货检验
                        double standardPrice = (double) priceMap.get(goodsNo);
                        colMap.put("F_PSUH_JSBZDJ", standardPrice);//标准成本单价
                        colMap.put("F_PSUH_JSBZCB", standardPrice * skuCount);//发货检验
                        FEntity.add(colMap);

                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee");//分摊后金额,对应金蝶含税单价
                double skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String unit = (String) unitMap.get(unitName);
                Map<String, Object> colMap = new LinkedHashMap<>();
                //金蝶单价为0就是赠品
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", skuCount);//实发数量
                //含税单价需要口减掉扣点 / 数量
                colMap.put("FTaxPrice", new BigDecimal(settPrice * (1 - points) / skuCount)
                        .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//含税单价
                //单价是0就是赠品
                if (settPrice == 0) {
                    colMap.put("FIsFree", true);//是否赠品
                } else {
                    colMap.put("FIsFree", false);//是否赠品
                }

                colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                double tax = (Double) taxMap.get(goodsNo);//获取税率
                colMap.put("FEntryTaxRate", tax);//税率
                colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                colMap.put("FEntroynote", goodsMemo);//货品备注
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSALUNITQTY", skuCount);//销售数量
                colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                colMap.put("FOUTCONTROL", false);//控制出库数量
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                colMap.put("FCheckDelivery", false);//发货检验
                double standardPrice = (double) priceMap.get(goodsNo);
                colMap.put("F_PSUH_JSBZDJ", standardPrice);//标准成本单价
                colMap.put("F_PSUH_JSBZCB", standardPrice * skuCount);//发货检验
                FEntity.add(colMap);
            }


        }

        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        historyDoc.append("param", payModel);
        String number = "";
        //创建销售出库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_OUTSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            if (e.getMessage().contains("货主组织已关账")) {
                //如果是因为关账原因没有上传成功的需要重新上传,日期为下个月的第一天
                String closeTime = e.getMessage().substring(48, 58);
                Date closeDate = VtuzxUtil.parseDate(closeTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(closeDate);
                calendar.add(Calendar.MONTH, 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);//当月第一天
                Date time = calendar.getTime();
                String firstTime = VtuzxUtil.formatYmdHmsF(time);
                syncKingdeeSaleOutPointAccount(client, data, historyDoc, storeDoc, firstTime, points);
            } else if (e.getMessage().contains("更新库存不成功!")) {
                syncKingdeeOtherInBill(client, data, historyDoc, storeDoc);
                kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            } else {
                _logger.info(tradeNo + e.getMessage());
                throw new VtuzxException(e.getMessage());
            }
        }

        return "";
    }

    /**
     * 野象销售出代扣点(因为关账日期无法上传的)
     *
     * @param client
     * @param data
     * @param historyDoc
     * @param storeDoc
     * @param firstTime
     */
    private String syncKingdeeSaleOutPointAccount(VtuzxKingdeeCloudClient client, VtuzxMap data, Document historyDoc, Document storeDoc, String firstTime, Double points) throws Exception {
        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data, "customerName");//客户名称
        //如果名称为空的话说明是没有结算单给与提示
        if (VtuzxUtil.isEmpty(customerName)) {
            historyDoc.append("message", "当前订单没有生成结算销售单,请生成结算销售单后在上传");
            return "当前订单没有生成结算销售单,请生成结算销售单后在上传";
        }
        String customerId = getCustomer(customerCode, client, storeDoc, customerName);
        String warehouseName = VtuzxUtil.getString(data, "warehouseName");//仓库名称(吉客云销售渠道)
        String shopName = VtuzxUtil.getString(data, "shopName");//店铺名称
        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        //如果查询不到销售渠道
        if (VtuzxUtil.isEmpty(channelDoc)) {
            historyDoc.append("message", "无法查询到销售渠道,请维护渠道");
            return "无法查询到销售渠道,请维护渠道";
        }
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号

        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        double otherFee = VtuzxUtil.getDouble(data, "otherFee");//销售费用
        double discountFee = VtuzxUtil.getDouble(data, "discountFee");//整单优惠
        double couponFee = VtuzxUtil.getDouble(data, "couponFee");//平台补贴(平台优惠)
        String sellerMemo = VtuzxUtil.getString(data, "sellerMemo");//备注(客服备注)
        String buyerMemo = VtuzxUtil.getString(data, "buyerMemo");//(买家备注)客户备注
        String appendMemo = VtuzxUtil.getString(data, "appendMemo");//追加备注
        String onlineTradeNo = VtuzxUtil.getString(data, "onlineTradeNo");//网店订单号
        String seller = VtuzxUtil.getString(data, "seller");//业务员
        String flagNames = VtuzxUtil.getString(data, "flagNames");//标记名称
        String createTime = VtuzxUtil.getString(data, "gmtCreate");//创建日期
        String tradeTime = VtuzxUtil.getString(data, "tradeTime");//下单时间
        String departName = VtuzxUtil.getString(data, "departName");//部门名称
        String invoiceStatus = VtuzxUtil.getString(data, "invoiceStatus");//是否开票
        String salesManId = "";
        if (!VtuzxUtil.isEmpty(seller)) {
            //如果部门没同步下来的话
            if (VtuzxUtil.isEmpty(departName)) {
                departName = getMainDepartName(seller, storeDoc);//吉客云部门名称
            }
            salesManId = getSellId(seller, client);//金蝶业务员id
        }

        String deliveryDeptId = "";//发货部门id
        if (!VtuzxUtil.isEmpty(departName)) {//如果吉客云部门名称不为空，查询金蝶部门id
            //查询发货部门id
            String cond = String.format("FName = '%s' and FForbidStatus ='%s'", departName, "A");
            List<VtuzxMap> bd_department = kingdeeService.query(client, "BD_Department", new VtuzxArrayList<>(
                    "FNumber",//=部门编码
                    "FNAME"//部门
            ), cond);
            if (bd_department != null && bd_department.size() > 0) {//如果有这个客户的话
                deliveryDeptId = (String) bd_department.get(0).get("FNumber");
            }
        }
        //如果发货部门为空的话不让传
        if (VtuzxUtil.isEmpty(deliveryDeptId)) {
            historyDoc.append("message", "无法查询到部门,请维护");
            return "无法查询到部门,请维护";
        }
        //在同步单据的时候会查询仓库id
        //存在没有仓库的情况,给与提示
        String stockId = VtuzxUtil.getString(data, "stockId");
        if (VtuzxUtil.isEmpty(stockId)) {
            historyDoc.append("message", "没有获取到仓库id,请重新同步单据");
            return "没有获取到仓库id,请重新同步单据";
        }
        String shopCustomerId = getCustomerShopName(client, departName);
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSCKD01_SYS"));//单据类型 标准销售出库单
        payModel.put("FDate", firstTime);//单据日期
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        //如果是外埠的客户还是正常客户
        if ("外埠".equals(channelGroup)) {
            payModel.put("FCustomerID", new Document("FNumber", customerId));//客户
        } else {//其他的传渠道信息
            payModel.put("FCustomerID", new Document("FNumber", shopCustomerId));//渠道
        }
        payModel.put("FSalesManID", new Document("FNumber", salesManId));//销售员
        payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织
        payModel.put("FDeliveryDeptID", new Document("FNumber", deliveryDeptId));//发货部门
        payModel.put("FSaleDeptID", new Document("FNumber", deliveryDeptId));//销售部门
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务或费用
        payModel.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
        payModel.put("F_ora_disFee", discountFee);//整单优惠
        payModel.put("F_ora_appendMemo", appendMemo);//追加备注
        payModel.put("F_ora_saleFee", otherFee);//销售费用
//        payModel.put("F_ora_kefuMemo",sellerMemo);//客服备注
        payModel.put("F_ora_kehuMemo", buyerMemo);//客户备注
        payModel.put("F_ora_lineTradeNo", onlineTradeNo);//网店单号
        payModel.put("F_PSUH_biaoji", flagNames);//标记
        payModel.put("F_PSUH_couponFee", couponFee);//平台补贴
        payModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        payModel.put("F_PSUH_DPMC", shopName);//店铺名称
        payModel.put("F_PSUH_KD", points);//扣点
        payModel.put("F_SXLJ_JKYKHBH", customerCode);//客户编号
        //如果是3的话为开票成功，其他为未开票
        if ("3".equals(invoiceStatus)) {
            payModel.put("F_PSUH_SFKP", true);//是否开票
        } else {
            payModel.put("F_PSUH_SFKP", false);//是否开票
        }

        //如果是寄存的单据,下单时间和创建时间在同月是正常销售单,不是同月的加一个寄存标记(为了不用算钱)
        if (flagNames.contains("寄存")) {
            if (!VtuzxUtil.isEmpty(tradeTime)) {
                String createSub = createTime.substring(5, 7);//创建日期月份
                String tradeSub = tradeTime.substring(5, 7);//下单日期月份
                if (!createSub.equals(tradeSub)) {
                    payModel.put("F_PSUH_JCBJ", "寄存");//寄存标记
                }
            }
        }
        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FIsIncludedTax", true);//是否含税
        SubHeadEntity.put("FLocalCurrID", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        SubHeadEntity.put("FIsPriceExcludeTax", true);//价外税
        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        //循环货品集合，添加金蝶单据体信息
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }

            taxMap.put(materialNo, Double.parseDouble(substring));
        }
        //查询价目表获取标准成本价
        Map<String, Object> priceMap = new HashMap<>();//key:物料编码 value : 标准成本
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            double standardPrice = VtuzxUtil.getDouble(priceDoc, "standardPrice");
            priceMap.put(materialNo, standardPrice);
        }
        //添加单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "ShareFavourableAfterFee");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        String cond = String.format("Fname = '%s'", unitName);
                        List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                                "FNumber",//物料编码
                                "FNAME"//物料名称
                        ), cond);
                        //获取物料编码
                        String unit = "";
                        if (bd_customer != null && bd_customer.size() > 0) {
                            unit = bd_customer.get(0).getString("FNumber");
                        }
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        //金蝶单价为0就是赠品
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", skuCount);//实发数量
                        //含税单价需要口减掉扣点
                        colMap.put("FTaxPrice", new BigDecimal(settPrice * (1 - points) / skuCount)
                                .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//含税单价
                        //单价是0就是赠品
                        if (settPrice == 0) {
                            colMap.put("FIsFree", true);//是否赠品
                        } else {
                            colMap.put("FIsFree", false);//是否赠品
                        }

                        colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                        colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                        double tax = (Double) taxMap.get(goodsNo);//获取税率
                        colMap.put("FEntryTaxRate", tax);//税率
                        colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                        colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                        colMap.put("FEntroynote", goodsMemo);//货品备注
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSALUNITQTY", skuCount);//销售数量
                        colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                        colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                        colMap.put("FOUTCONTROL", false);//控制出库数量
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                        colMap.put("FCheckDelivery", false);//发货检验
                        double standardPrice = (double) priceMap.get(goodsNo);
                        colMap.put("F_PSUH_JSBZDJ", standardPrice);//标准成本单价
                        colMap.put("F_PSUH_JSBZCB", standardPrice * skuCount);//发货检验
                        FEntity.add(colMap);

                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee");//分摊后金额,对应金蝶含税单价
                double skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",//物料编码
                        "FNAME"//物料名称
                ), cond);
                //获取物料编码
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }
                Map<String, Object> colMap = new LinkedHashMap<>();
                //金蝶单价为0就是赠品
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", skuCount);//实发数量
                //含税单价需要口减掉扣点 / 数量
                colMap.put("FTaxPrice", new BigDecimal(settPrice * (1 - points) / skuCount)
                        .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//含税单价
                //单价是0就是赠品
                if (settPrice == 0) {
                    colMap.put("FIsFree", true);//是否赠品
                } else {
                    colMap.put("FIsFree", false);//是否赠品
                }

                colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                double tax = (Double) taxMap.get(goodsNo);//获取税率
                colMap.put("FEntryTaxRate", tax);//税率
                colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                colMap.put("FEntroynote", goodsMemo);//货品备注
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSALUNITQTY", skuCount);//销售数量
                colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                colMap.put("FOUTCONTROL", false);//控制出库数量
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                colMap.put("FCheckDelivery", false);//发货检验
                double standardPrice = (double) priceMap.get(goodsNo);
                colMap.put("F_PSUH_JSBZDJ", standardPrice);//标准成本单价
                colMap.put("F_PSUH_JSBZCB", standardPrice * skuCount);//发货检验
                FEntity.add(colMap);
            }


        }

        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        historyDoc.append("param", payModel);
        String number = "";
        //创建销售出库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_OUTSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            if (e.getMessage().contains("更新库存不成功")) {
                syncKingdeeOtherInBill(client, data, historyDoc, storeDoc);
                kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            } else {
                throw new VtuzxException(e.getMessage());
            }


        }

        return "";

    }


    //金蝶采购入(野象)
    private void syncKingdeeProcure(VtuzxKingdeeCloudClient client, Document data, Document historyDoc, Document storeDoc) throws Exception {

//        String outReldataName = VtuzxUtil.getString(data,"outReldataName");//接受方

        String orderNo = VtuzxUtil.getString(data, "orderNo");
        Long settDate = VtuzxUtil.getObject(data, "settDate");//创建时间
        String orderTime = VtuzxUtil.getString(data, "orderTime");//创建时间
        String stockId = VtuzxUtil.getObject(data, "stockId");//金蝶仓库id
        //存在无法查询到仓库的情况,给一个默认仓库
        if (VtuzxUtil.isEmpty(stockId)) {
            stockId = "YXWB01";
        }

        Map<String, Object> model = new LinkedHashMap<>();//采购入库api总参
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID", new Document("FNUMBER", "RKD01_SYS"));//单据类型标准采购入库单
        if (!VtuzxUtil.isEmpty(orderTime)) {
            model.put("FDate", orderTime);//入库日期
        } else {
            model.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));//入库日期
        }

//        model.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));//入库日期
        model.put("FStockOrgId", new Document("FNumber", "200"));//收料组织，开发销售测试
//        model.put("FStockDeptId", new Document("FNumber", departMentId));//收料部门
        model.put("FDemandOrgId", new Document("FNumber", "200"));//需求组织，开发销售测试
        model.put("FPurchaseOrgId", new Document("FNumber", "200"));//采购组织，开发销售测试
//        model.put("FPurchaseDeptId", new Document("FNumber", departMentId));//采购部门
        model.put("FSupplierId", new Document("FNumber", "05.0002"));//应收公司晓芹，野象传采购入，供应商是晓芹
//        model.put("FSupplyId", new Document("FNumber", "01.0001"));//供货方晓芹
//        model.put("FSettleId", new Document("FNumber", "05.0002"));//结算方也是晓芹
//        model.put("FChargeId", new Document("FNumber", "05.0002"));//收款方晓芹
        model.put("FCorrespondOrgId", new Document("FNumber", "200"));//对应组织
        model.put("FIsInterLegalPerson", false);//组织间结算跨法人标识
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        model.put("FOwnerIdHead", new Document("FNumber", "200"));//货主
        model.put("FSplitBillType", "A");//拆单类型
        model.put("F_ora_SJLY", orderNo);//数据来源 先存放极客云结算单号
        model.put("FInStockFin", new Document("FSettleOrgId", new Document("FNumber", "200")));//结算信息里的结算组织
        model.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别 人名币
        model.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        model.put("F_PSUH_JSDH", orderNo);//吉客云结算单号

        List<Map<String, Object>> FInStockEntry = new ArrayList<>();//采购入库体数据
        //根据结算单号查询货品信息
        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合

        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
            Document getGoods = (Document) goodsMap.get(goodsNo);
            if (!materialNoList.contains(goodsNo)) {
                materialNoList.add(goodsNo);
            }
            if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                goodsMap.put(goodsNo, doc);
            } else {
                double skuCount = VtuzxUtil.getDouble(doc, "skuCount");
                double skuNowCount = VtuzxUtil.getDouble(getGoods, "skuCount");
                doc.replace("skuCount", skuCount + skuNowCount);
                goodsMap.put(goodsNo, doc);
            }
        }
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称

            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }

        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");

            priceMap.put(materialNo, currentPrice);
        }
        //循环货品集合，添加金蝶单据体信息
        for (Map.Entry entry : goodsMap.entrySet()) {
            Document doc = (Document) entry.getValue();
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");//货品编号
//            double settPrice = VtuzxUtil.getDouble(doc, "settPrice");//结算金额
            double settPrice = VtuzxUtil.getDouble(priceMap, goodsNo);
            String unitName = VtuzxUtil.getString(doc, "unitName");
            double skuCount = VtuzxUtil.getDouble(doc, "skuCount");

            //查询单位编码，直接传文字无效
            String unit = (String) unitMap.get(unitName);
            if (VtuzxUtil.isEmpty(unit)) {
                throw new VtuzxException(String.format("物料:%s不存在", goodsNo));
            }

            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
            colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
            colMap.put("FRealQty", skuCount);//实收数量
            colMap.put("FPriceUnitID", new Document("FNumber", unit));//计价单位
//                colMap.put("FLot", new Document("FNumber", "88888"));//批号
//            colMap.put("FStockId", new Document("FNumber", stockId));//仓库
            colMap.put("FStockId", new Document("FNumber", "001"));//仓库
            colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            colMap.put("FGiveAway", false);//是否正品
            colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
            colMap.put("FCheckInComing", false);//来料校验
            colMap.put("FIsReceiveUpdateStock", false);//收料后更新库存状态
            colMap.put("FPriceBaseQty", skuCount);//计价基本数量
            colMap.put("FRemainInStockUnitId", new Document("FNumber", unit));//采购单位
            colMap.put("FBILLINGCLOSE", false);//立账关闭
            colMap.put("FRemainInStockQty", skuCount);//采购数量
            colMap.put("FAPNotJoinQty", skuCount);//未关联应付数量（计价单位
            colMap.put("FRemainInStockBaseQty", skuCount);//采购基本数量
            double tax = VtuzxUtil.getDouble(taxMap, goodsNo);//税率

            colMap.put("FEntryTaxRate", tax);//税率
            colMap.put("FTaxPrice", settPrice);//含税单价
            if (settPrice == 0) {
                colMap.put("FGiveAway", true);//是否赠品
            }
            colMap.put("FOWNERID", new Document("FNumber", "200"));//货主开发销售测试
            FInStockEntry.add(colMap);
        }


        model.put("FInStockEntry", FInStockEntry);
        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", true);
        kneeParam.put("IsEntryBatchFill", false);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", model);
        //野象创建采购入库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "STK_InStock", kneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "STK_InStock", "0", number);
            kingdeeService.audit(client, "STK_InStock", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(orderNo + e.getMessage());
            throw new VtuzxException(e.getMessage());
        }

    }

    //金蝶采购入(野象)Task
    private void syncKingdeeProcureTask(VtuzxKingdeeCloudClient client, Document data, VtuzxMap materialMap, List<Document> dataList, Document historyDoc, VtuzxMap FID) throws Exception {
        String goodsNo;
        double taxRate;
        String unit;
        double price;
        List<Map<String, Object>> FInStockEntry = new ArrayList<>();
        Map<String, Object> priceMap = VtuzxUtil.getObject(FID, "priceMap");
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        for (Document procureIn : dataList) {
            Document doc = new Document(procureIn);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> fitOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(fitOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        Map<String, Object> procureInMap = new LinkedHashMap<>();
                        if (VtuzxUtil.isEmpty(VtuzxUtil.getString(fitOrder, "GoodsNo"))) {
                            goodsNo = VtuzxUtil.getString(fitOrder, "goodsNo");
                            List<String> fitMaterialNoList = new ArrayList<>();//组合装物料编码集合
                            if (!fitMaterialNoList.contains(goodsNo)) {
                                fitMaterialNoList.add(goodsNo);
                            }
                            //查询价目表获取价格信息
                            Iterator<Document> fitPriceItr = priceListDao.findList(Criteria.where("materialNo").in(fitMaterialNoList), null, 0, 0);
                            Map<String, Object> fitPriceMap = new HashMap<>();//key : 物料编码 val:初始供货价
                            while (fitPriceItr.hasNext()) {
                                Document fitPriceDoc = fitPriceItr.next();
                                String materialNo = VtuzxUtil.getString(fitPriceDoc, "materialNo");
                                Double currentPrice = VtuzxUtil.getDouble(fitPriceDoc, "currentPrice");
                                fitPriceMap.put(materialNo, currentPrice);
                            }
                            price = (double) fitPriceMap.get(goodsNo);//含税单价
                            VtuzxMap materialDoc = VtuzxUtil.getObject(fitOrder, goodsNo);
                            taxRate = VtuzxUtil.getDouble(materialDoc, "taxRate");
                            unit = VtuzxUtil.getString(materialDoc, "unit");
                        } else {
                            goodsNo = VtuzxUtil.getString(fitOrder, "GoodsNo");
//                            price = VtuzxUtil.getDouble(fitOrder, "ShareFavourableAfterFee");//含税单价
                            List<String> fitMaterialNoList = new ArrayList<>();//组合装物料编码集合
                            if (!fitMaterialNoList.contains(goodsNo)) {
                                fitMaterialNoList.add(goodsNo);
                            }
                            //查询价目表获取价格信息
                            Iterator<Document> fitPriceItr = priceListDao.findList(Criteria.where("materialNo").in(fitMaterialNoList), null, 0, 0);
                            Map<String, Object> fitPriceMap = new HashMap<>();//key : 物料编码 val:初始供货价
                            while (fitPriceItr.hasNext()) {
                                Document fitPriceDoc = fitPriceItr.next();
                                String materialNo = VtuzxUtil.getString(fitPriceDoc, "materialNo");
                                Double currentPrice = VtuzxUtil.getDouble(fitPriceDoc, "currentPrice");
                                fitPriceMap.put(materialNo, currentPrice);
                            }
                            price = (double) fitPriceMap.get(goodsNo);//含税单价
//                            VtuzxMap materialDoc = VtuzxUtil.getObject(fitOrder, goodsNo);
                            taxRate = VtuzxUtil.getDouble(fitOrder, "TaxRate");
                            unit = VtuzxUtil.getString(fitOrder, "Unit");
                        }
                        String unitId = "";
                        //查询单位编码
                        String cond = String.format("Fname = '%s'", unit);
                        List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                                "FNumber",
                                "FNAME"
                        ), cond);
                        if (bd_customer != null && bd_customer.size() > 0) {
                            unitId = bd_customer.get(0).getString("FNumber");
                        }
                        //判断是否启用批号
                        String floatCond = String.format("FNumber = '%s'", goodsNo);
                        List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                "FIsBatchManage"
                        ), floatCond);
                        //获取单位编码
                        boolean flag = true;
                        if (bd_Material != null && bd_Material.size() > 0) {
                            flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                        }
                        double count = 0.0;
                        if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "tradeNo"))) {
                            count = VtuzxUtil.getDouble(fitOrder, "skuCount");
                        } else {
                            count = VtuzxUtil.getDouble(fitOrder, "SellCount");
                        }
                        procureInMap.put("FRowType", "Standard");
                        procureInMap.put("FMaterialID", new VtuzxMap("FNumber", goodsNo));
                        procureInMap.put("FUnitID", new VtuzxMap("FNumber", unitId));
                        procureInMap.put("FRealQty", Math.abs(count));
                        procureInMap.put("FOwnerTypeID", "BD_OwnerOrg");
                        String flagForFOwnerID = VtuzxUtil.getString(FID, "flagForFOwnerID");
                        procureInMap.put("FOwnerID", new Document("FNumber", flagForFOwnerID));
//                        procureInMap.put("FEntryTaxRate", taxRate);
                        String flagForFStockID = VtuzxUtil.getString(FID, "flagForFStockID");
                        procureInMap.put("FStockID", new Document("FNumber", flagForFStockID));//仓库
                        String flagForFOWNERID = VtuzxUtil.getString(FID, "flagForFOWNERID");
                        procureInMap.put("FOWNERID", new VtuzxMap("FNumber", flagForFOWNERID));//货主
                        procureInMap.put("FTaxPrice", Math.abs(price));//含税单价
                        if (price == 0) {
                            procureInMap.put("FIsFree", true);//是否赠品
                        } else {
                            procureInMap.put("FIsFree", false);//是否赠品
                        }
                        procureInMap.put("FStockStatusID", new VtuzxMap("FNumber", "KCZT01_SYS"));
                        procureInMap.put("FSalUnitID", new VtuzxMap("FNumber", unitId));
                        procureInMap.put("FSALUNITQTY", count);
                        procureInMap.put("FSALBASEQTY", count);
                        procureInMap.put("FPRICEBASEQTY", count);
                        procureInMap.put("FOUTCONTROL", false);
                        procureInMap.put("FIsOverLegalOrg", false);
                        procureInMap.put("FARNOTJOINQTY", count);
                        procureInMap.put("FCheckDelivery", false);
                        FInStockEntry.add(procureInMap);
                    }
                }
            } else {
                Map<String, Object> procureInMap = new LinkedHashMap<>();
                if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "tradeNo"))) {
                    goodsNo = VtuzxUtil.getString(procureIn, "goodsNo");
                    price = (double) priceMap.get(goodsNo);//含税单价
                    VtuzxMap materialDoc = VtuzxUtil.getObject(materialMap, goodsNo);
                    taxRate = VtuzxUtil.getDouble(materialDoc, "taxRate");
                    unit = VtuzxUtil.getString(materialDoc, "unit");
                } else {
                    goodsNo = VtuzxUtil.getString(procureIn, "GoodsNo");
//                    price = VtuzxUtil.getDouble(procureIn, "ShareFavourableAfterFee");//含税单价
                    price = (double) priceMap.get(goodsNo);//含税单价
                    VtuzxMap materialDoc = VtuzxUtil.getObject(materialMap, goodsNo);
                    taxRate = VtuzxUtil.getDouble(materialDoc, "TaxRate");
                    if(VtuzxUtil.isEmpty(VtuzxUtil.getString(materialDoc, "Unit"))){
                        unit = VtuzxUtil.getString(materialDoc, "unit");
                    } else {
                        unit = VtuzxUtil.getString(materialDoc, "Unit");
                    }
                }
                String unitId = "";
                //查询单位编码
                String cond = String.format("Fname = '%s'", unit);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",
                        "FNAME"
                ), cond);
                if (bd_customer != null && bd_customer.size() > 0) {
                    unitId = bd_customer.get(0).getString("FNumber");
                }
                //判断是否启用批号
                String floatCond = String.format("FNumber = '%s'", goodsNo);
                List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FIsBatchManage"
                ), floatCond);
                //获取单位编码
                boolean flag = true;
                if (bd_Material != null && bd_Material.size() > 0) {
                    flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                }
                double count = 0.0;
                if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "tradeNo"))) {
                    count = VtuzxUtil.getDouble(procureIn, "skuCount");
                } else {
                    count = VtuzxUtil.getDouble(procureIn, "SellCount");
                }
                procureInMap.put("FRowType", "Standard");
                procureInMap.put("FMaterialID", new VtuzxMap("FNumber", goodsNo));
                procureInMap.put("FUnitID", new VtuzxMap("FNumber", unitId));
                procureInMap.put("FRealQty", Math.abs(count));
                procureInMap.put("FOwnerTypeID", "BD_OwnerOrg");
                String flagForFOwnerID = VtuzxUtil.getString(FID, "flagForFOwnerID");
                procureInMap.put("FOwnerID", new Document("FNumber", flagForFOwnerID));
//                procureInMap.put("FEntryTaxRate", taxRate);
                String flagForFStockID = VtuzxUtil.getString(FID, "flagForFStockID");
                procureInMap.put("FStockID", new Document("FNumber", flagForFStockID));//仓库
                String flagForFOWNERID = VtuzxUtil.getString(FID, "flagForFOWNERID");
                procureInMap.put("FOWNERID", new VtuzxMap("FNumber", flagForFOWNERID));//货主
                procureInMap.put("FTaxPrice", Math.abs(price));//含税单价
                if (price == 0) {
                    procureInMap.put("FIsFree", true);//是否赠品
                } else {
                    procureInMap.put("FIsFree", false);//是否赠品
                }
                procureInMap.put("FStockStatusID", new VtuzxMap("FNumber", "KCZT01_SYS"));
                procureInMap.put("FSalUnitID", new VtuzxMap("FNumber", unitId));
                procureInMap.put("FSALUNITQTY", count);
                procureInMap.put("FSALBASEQTY", count);
                procureInMap.put("FPRICEBASEQTY", count);
                procureInMap.put("FOUTCONTROL", false);
                procureInMap.put("FIsOverLegalOrg", false);
                procureInMap.put("FARNOTJOINQTY", count);
                procureInMap.put("FCheckDelivery", false);
                FInStockEntry.add(procureInMap);
            }
        }
        Map<String, Object> model = new LinkedHashMap<>();//采购入库api总参
        model.put("FID", 0);//实体主键
        String JKYDH = "";
        if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "allocateNo"))) {
            JKYDH = VtuzxUtil.getString(data, "tradeNo");
            model.put("F_PSUH_XSDH", JKYDH);
        } else if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "tradeNo"))) {
            JKYDH = VtuzxUtil.getString(data, "allocateNo");
            model.put("F_PSUH_JSDH", JKYDH);
        }
        model.put("FBillTypeID", new Document("FNUMBER", "RKD01_SYS"));//单据类型标准采购入库单
        String flagFStockOrgId = VtuzxUtil.getString(FID, "flagFStockOrgId");
        model.put("FStockOrgId", new VtuzxMap("FNumber", flagFStockOrgId));//收料组织
        String flagFDemandOrgId = VtuzxUtil.getString(FID, "flagFDemandOrgId");
        model.put("FDemandOrgId", new VtuzxMap("FNumber", flagFDemandOrgId));//需求组织
        String flagFPurchaseOrgId = VtuzxUtil.getString(FID, "flagFPurchaseOrgId");
        model.put("FPurchaseOrgId", new VtuzxMap("FNumber", flagFPurchaseOrgId));//采购组织
        String flagFSupplierId = VtuzxUtil.getString(FID, "flagFSupplierId");
        model.put("FSupplierId", new VtuzxMap("FNumber", flagFSupplierId));//应收公司
        String flagFCorrespondOrgId = VtuzxUtil.getString(FID, "flagFCorrespondOrgId");
        model.put("FCorrespondOrgId", new VtuzxMap("FNumber", flagFCorrespondOrgId));//对应组织
        model.put("FIsInterLegalPerson", false);//组织间结算跨法人标识
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        String flagFOwnerIdHead = VtuzxUtil.getString(FID, "flagFOwnerIdHead");
        model.put("FOwnerIdHead", new VtuzxMap("FNumber", flagFOwnerIdHead));//货主
        model.put("FSplitBillType", "A");//拆单类型
        model.put("FInStockFin", new Document("FSettleOrgId", new Document("FNumber", "200")));//结算信息里的结算组织
        model.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别 人名币
        model.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        model.put("FInStockEntry", FInStockEntry);
        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", true);
        kneeParam.put("IsEntryBatchFill", false);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", model);
        historyDoc.append("param", new VtuzxMap("STK_InStock", kneeParam));
        //野象创建采购入库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "STK_InStock", kneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "STK_InStock", "0", number);
            kingdeeService.audit(client, "STK_InStock", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
            historyDoc.append("syncTask", true);
        } catch (Exception e) {
            throw new VtuzxException(e.getMessage());
        }
    }

    //晓芹采购入
    private void syncKingdeeProcureXQ(VtuzxKingdeeCloudClient client, Document data, Document historyDoc) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String orderNo = VtuzxUtil.getString(data, "orderNo");
        Long settDate = VtuzxUtil.getObject(data, "settDate");//创建时间
        String inReldataName = VtuzxUtil.getString(data, "inReldataName");//接收方

        String stockId = "";//仓库id

        if (inReldataName.contains("外埠")) {
            stockId = "YXWB01";
        } else {
            //去仓库接口查询部门和仓库
            VtuzxMap stockMap = new VtuzxMap();
            stockMap.append("pageIndex", 0).append("pageSize", 1).append("name", inReldataName);
            VtuzxMap stock = jiKeYunApiService.getStock(storeDoc, stockMap);
            Map<String, Object> result = VtuzxUtil.getObject(stock, "result");
            Map<String, Object> stockData = VtuzxUtil.getObject(result, "data");
            List<Map<String, Object>> warehouseInfo = VtuzxUtil.getObject(stockData, "warehouseInfo");
            if (!VtuzxUtil.isEmpty(warehouseInfo)) {
                stockId = VtuzxUtil.getString(warehouseInfo.get(0), "warehouseCode");//获取仓库编号
            }


        }

        Map<String, Object> model = new LinkedHashMap<>();//采购入库api总参
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID", new Document("FNUMBER", "RKD01_SYS"));//单据类型标准采购入库单
        model.put("FDate", VtuzxUtil.formatYmdHmsF(new Date(settDate)));//入库日期
        model.put("FStockOrgId", new Document("FNumber", "100"));//收料组织，开发销售测试
//        model.put("FStockDeptId", new Document("FNumber", departMentId));//收料部门
        model.put("FDemandOrgId", new Document("FNumber", "100"));//需求组织，开发销售测试
        model.put("FPurchaseOrgId", new Document("FNumber", "100"));//采购组织，开发销售测试
//        model.put("FPurchaseDeptId", new Document("FNumber", departMentId));//采购部门
        model.put("FSupplierId", new Document("FNumber", "VEN00047"));//应收公司野象
        model.put("FSupplyId", new Document("FNumber", "VEN00047"));//供货方野象
        model.put("FSettleId", new Document("FNumber", "VEN00047"));//结算方也是野象
        model.put("FChargeId", new Document("FNumber", "VEN00047"));//收款方野象
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        model.put("FOwnerIdHead", new Document("FNumber", "100"));//货主
        model.put("FSplitBillType", "A");//拆单类型
        model.put("F_ora_SJLY", orderNo);//数据来源 先存放极客云结算单号
        model.put("FInStockFin", new Document("FSettleOrgId", new Document("FNumber", "100")));//结算信息里的结算组织
        model.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别 人名币
        model.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        model.put("F_CGRK_JKYDJH", orderNo);

        List<Map<String, Object>> FInStockEntry = new ArrayList<>();//采购入库体数据
        //根据结算单号查询货品信息
        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合

        Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
            Document getGoods = (Document) goodsMap.get(goodsNo);
            if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                goodsMap.put(goodsNo, doc);
            } else {
                int skuCount = VtuzxUtil.getInt(doc, "skuCount");
                int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                doc.replace("skuCount", skuCount + skuNowCount);
                goodsMap.put(goodsNo, doc);
            }
        }
        //循环货品集合，添加金蝶单据体信息
        for (Map.Entry entry : goodsMap.entrySet()) {
            Document doc = (Document) entry.getValue();
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");//货品编号
            double settPrice = VtuzxUtil.getDouble(doc, "settPrice");//结算金额
            double taxRate = VtuzxUtil.getDouble(doc, "taxRate");//税率
            String unitName = VtuzxUtil.getString(doc, "unitName");
            int skuCount = VtuzxUtil.getInt(doc, "skuCount");

            //查询单位编码，直接传文字无效
            String cond = String.format("Fname = '%s'", unitName);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                    "FNumber",
                    "FNAME"
            ), cond);
            //获取客户编码(往来单位)
            String unit = "";
            if (bd_customer != null && bd_customer.size() > 0) {
                unit = bd_customer.get(0).getString("FNumber");
            }
            //判断是否启用批号
            String floatCond = String.format("FNumber = '%s'", goodsNo);
            List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                    "FIsBatchManage"
            ), floatCond);
            //获取单位编码
            boolean flag = true;
            if (bd_Material != null && bd_Material.size() > 0) {
                flag = bd_Material.get(0).getBoolean("FIsBatchManage");

            }
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
            colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
            colMap.put("FRealQty", skuCount);//实收数量
            colMap.put("FPriceUnitID", new Document("FNumber", unit));//计价单位
            if (flag) {
                colMap.put("FLot", new Document("FNumber", "88888"));//批号
            }

            colMap.put("FStockId", new Document("FNumber", stockId));//仓库
            colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            colMap.put("FGiveAway", false);//是否正品
            colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
            colMap.put("FCheckInComing", false);//来料校验
            colMap.put("FIsReceiveUpdateStock", false);//收料后更新库存状态
            colMap.put("FPriceBaseQty", skuCount);//计价基本数量
            colMap.put("FRemainInStockUnitId", new Document("FNumber", unit));//采购单位
            colMap.put("FBILLINGCLOSE", false);//立账关闭
            colMap.put("FRemainInStockQty", skuCount);//采购数量
            colMap.put("FAPNotJoinQty", skuCount);//未关联应付数量（计价单位
            colMap.put("FRemainInStockBaseQty", skuCount);//采购基本数量
            colMap.put("FEntryTaxRate", taxRate);//税率
            colMap.put("FTaxPrice", settPrice);//含税单价
            colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
            FInStockEntry.add(colMap);
        }


        model.put("FInStockEntry", FInStockEntry);
        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", true);
        kneeParam.put("IsEntryBatchFill", false);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", model);
        //晓芹创建采购入库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "STK_InStock", kneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "STK_InStock", "0", number);
            kingdeeService.audit(client, "STK_InStock", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(orderNo + e.getMessage());
//            throw new VtuzxException(e.getMessage());
        }

    }

    //野象销售出(销售单)
    private String syncKingdeeSaleOutOne(VtuzxKingdeeCloudClient client, VtuzxMap data, Document historyDoc, Document storeDoc) throws Exception {

        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data, "customerName");//客户名称
        String orderTime = VtuzxUtil.getString(historyDoc, "orderTime");//客户名称
        if (VtuzxUtil.isEmpty(customerName)) {
            historyDoc.append("message", "销售单未结算,无法查询到客户信息,请先结算");
            return "销售单未结算,无法查询到客户信息,请先结算";
        }
        //查询客户
        String customerId = getCustomer(customerCode, client, storeDoc, customerName);
        String warehouseName = VtuzxUtil.getString(data, "warehouseName");//仓库名称(吉客云销售渠道)
        String shopName = VtuzxUtil.getString(data, "shopName");//店铺名称
        if ("bb044山东路专卖店-野象".equals(shopName)) {
            shopName = "bb045山东路专卖店-野象";
        }
        //外埠的不要做截取，野象-展示厅不要截取，天猫的不要做截取
        if (shopName.contains("-") && !shopName.contains("外埠") && !shopName.startsWith("bb") && !shopName.contains("展示厅") && !shopName.contains("天猫") && !shopName.startsWith("百年晓芹")) {
            shopName = shopName.substring(0, shopName.indexOf("-"));
        }
        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        //如果查询不到销售渠道
        if (VtuzxUtil.isEmpty(channelDoc)) {
            historyDoc.append("message", "无法查询到销售渠道,请维护渠道");
            return "无法查询到销售渠道,请维护渠道";
        }
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号

        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        double otherFee = VtuzxUtil.getDouble(data, "otherFee");//销售费用
        double discountFee = VtuzxUtil.getDouble(data, "discountFee");//整单优惠
        double couponFee = VtuzxUtil.getDouble(data, "couponFee");//平台补贴(平台优惠)
        String sellerMemo = VtuzxUtil.getString(data, "sellerMemo");//备注(客服备注)
        String buyerMemo = VtuzxUtil.getString(data, "buyerMemo");//(买家备注)客户备注
        String appendMemo = VtuzxUtil.getString(data, "appendMemo");//追加备注
        String onlineTradeNo = VtuzxUtil.getString(data, "onlineTradeNo");//网店订单号
        String seller = VtuzxUtil.getString(data, "seller");//业务员
        String flagNames = VtuzxUtil.getString(data, "flagNames");//标记名称
        String createTime = VtuzxUtil.getString(data, "gmtCreate");//创建日期
//        Date consignTime = VtuzxUtil.getObject(data,"consignTime");//发货日期
        String invoiceStatus = VtuzxUtil.getString(data, "invoiceStatus");//是否开票
        //同步数据时会同步部门,后加的
        String departName = VtuzxUtil.getString(data, "departName");//部门
        String salesManId = "";
        if (!VtuzxUtil.isEmpty(seller)) {
            //如果部门没同步下来的话
            if (VtuzxUtil.isEmpty(departName)) {
                departName = getMainDepartName(seller, storeDoc);//吉客云部门名称
            }
            salesManId = getSellId(seller, client);//金蝶业务员id
        }


        //渠道是爱你商城传金蝶部门为市场部，客户为爱你商城
        if ("爱你商城".equals(shopName)) {
            departName = "市场部";
        } else if (shopName.startsWith("外埠")) {
            departName = shopName;
        }

        if (departName.contains("外埠")) {//如果部门为外埠固定传(因为吉客云和金蝶部门名称没统一)
            departName = "外埠（营销外埠）";
        } else if (departName.contains("网购") || departName.contains("营销三部")) {
            departName = "网购（营销网购）";
        } else if (departName.contains("bb044")) {
            departName = "bb045山东路专卖店";
        } else if (departName.contains("本埠（二）")) {
            departName = "bb047比优特三八广场店";
        } else if (departName.contains("客服部")) {
            departName = "客户信息服务部";
        }
        //查询部门的时候加上禁用状态
        String deliveryDeptId = "";//发货部门id
        String qdNo = "";//渠道编码
        if (!VtuzxUtil.isEmpty(departName)) {//如果吉客云部门名称不为空，查询金蝶部门id
            //查询发货部门id
            String cond = String.format("FName = '%s' and FForbidStatus ='%s'", departName, "A");
            List<VtuzxMap> bd_department = kingdeeService.query(client, "BD_Department", new VtuzxArrayList<>(
                    "FNumber",//=部门编码
                    "FNAME"//部门
            ), cond);
            if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                deliveryDeptId = (String) bd_department.get(0).get("FNumber");
            }

            //查询客户外埠的根据客户查询，其他的根据部门查询
            if (departName.startsWith("外埠")) {
                String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", customerName, "A");
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                        "FNumber",//客户编码
                        "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                        "FNAME"//客户名称
                ), cusCond);
                if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                    qdNo = VtuzxUtil.getString(bd_customer.get(0), "F_SXLJ_xsqd.FNUMBER");
                }
            } else {
                String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", departName, "A");
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                        "FNumber",//客户编码
                        "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                        "FNAME"//客户名称
                ), cusCond);
                if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                    qdNo = VtuzxUtil.getString(bd_customer.get(0), "F_SXLJ_xsqd.FNUMBER");
                }
            }

        }


        //如果发货部门为空的话不让传
        if (VtuzxUtil.isEmpty(deliveryDeptId)) {
            historyDoc.append("message", "无法查询到部门,请维护");
            return "无法查询到部门,请维护";
        }

        //在同步单据的时候会查询仓库id
        //存在没有仓库的情况,给与提示
        String stockId = VtuzxUtil.getString(data, "stockId");
        if (VtuzxUtil.isEmpty(stockId)) {
            historyDoc.append("message", "没有获取到仓库id,请重新同步单据");
            return "没有获取到仓库id,请重新同步单据";
        }
        //查询客户(门店通过部门查询客户，其他的通过渠道查询)
        String shopCustomerId = "";
        if (shopName.startsWith("bb")) {
            shopCustomerId = getCustomerShopName(client, departName);
        } else {
            //添加门店渠道中的对应关系
            if ("野象考拉店铺".equals(shopName)) {
                shopName = "网易考拉";
            } else if ("野象苏宁超市".equals(shopName)) {
                shopName = "苏宁超市";
            } else if ("客服外卖-代收货款".equals(shopName)) {
                shopName = "客服外卖";
            } else if ("野象-展示厅".equals(shopName)) {
                shopName = "展示厅";
            } else if ("天猫超市-野象".equals(shopName)) {
                shopName = "天猫超市";
            } else if ("客服外卖".equals(shopName)) {
                shopName = "客户信息服务部";
            } else if ("特渠库".equals(shopName)) {
                shopName = "客户信息服务部";
            } else if ("杭州光年有限公司".equals(shopName)) {
                shopName = "光年（杭州）水产品";
            } else if ("天猫旗舰店-野象".equals(shopName)) {
                shopName = "天猫商城";
            } else if ("百年晓芹-拼多多生鲜".equals(shopName)) {
                shopName = "拼多多-生鲜";
            }
            shopCustomerId = getCustomerShopName(client, shopName);
        }
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSCKD01_SYS"));//单据类型 标准销售出库单
        if (!VtuzxUtil.isEmpty(orderTime)) {
            payModel.put("FDate", orderTime);//发货日期
        } else {
            payModel.put("FDate", createTime);//单据日期
        }
//        payModel.put("FDate",VtuzxUtil.formatYmdHmsF(new Date()));
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织

        //如果是外埠的客户还是正常客户
        if ("外埠".equals(channelGroup) || shopName.startsWith("外埠")) {
            payModel.put("FCustomerID", new Document("FNumber", customerId));//客户
            payModel.put("FReceiverID", new Document("FNumber", customerId));//收货方
            payModel.put("FStockOrgId", new Document("FNumber", "200"));//发货组织(200)
            payModel.put("FSettleID", new Document("FNumber", customerId));//结算方
            payModel.put("FPayerID", new Document("FNumber", customerId));//付款方
        } else {//其他的传渠道信息,渠道是特渠库也传客户
            if ("特渠库".equals(shopName)) {
                payModel.put("FCustomerID", new Document("FNumber", customerId));//客户
                payModel.put("FReceiverID", new Document("FNumber", customerId));//收货方
                payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织(200)
                payModel.put("FSettleID", new Document("FNumber", customerId));//结算方
                payModel.put("FPayerID", new Document("FNumber", customerId));//付款方
            } else {
                payModel.put("FCustomerID", new Document("FNumber", shopCustomerId));//渠道
                payModel.put("FReceiverID", new Document("FNumber", shopCustomerId));//收货方
                if (shopName.startsWith("bb")) {
                    payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织(200)
                } else {
                    payModel.put("FStockOrgId", new Document("FNumber", "200"));//发货组织(200)
                }
//                payModel.put("FStockOrgId", new Document("FNumber", "200"));//发货组织(200)
                payModel.put("FSettleID", new Document("FNumber", shopCustomerId));//结算方
                payModel.put("FPayerID", new Document("FNumber", shopCustomerId));//付款方
            }

        }

        payModel.put("FDeliveryDeptID", new Document("FNumber", "01"));//发货部门
        payModel.put("FSaleDeptID", new Document("FNumber", deliveryDeptId));//销售部门
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FCDateOffsetValue", 0);//创建日期
        payModel.put("FIsTotalServiceOrCost", false);//整单服务或费用
        payModel.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
        payModel.put("F_ora_disFee", discountFee);//整单优惠
        payModel.put("F_ora_appendMemo", appendMemo);//追加备注
        payModel.put("F_ora_saleFee", otherFee);//销售费用
//        payModel.put("F_ora_kefuMemo",sellerMemo);//客服备注
        payModel.put("F_ora_kehuMemo", buyerMemo);//客户备注
        payModel.put("F_ora_lineTradeNo", onlineTradeNo);//网店订单号
        payModel.put("F_PSUH_biaoji", flagNames);//标记
        payModel.put("F_PSUH_couponFee", couponFee);//平台补贴
        payModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        payModel.put("F_PSUH_DPMC", shopName);//店铺名称
        payModel.put("F_PSUH_KH", customerName);//客户名称
        payModel.put("F_SXLJ_JKYKHBH", customerCode);//客户编号
        //如果是3的话为开票成功，其他为未开票
        if ("3".equals(invoiceStatus)) {
            payModel.put("F_PSUH_SFKP", true);//是否开票
        } else {
            payModel.put("F_PSUH_SFKP", false);//是否开票
        }

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FIsIncludedTax", true);//是否含税
        SubHeadEntity.put("FLocalCurrID", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        SubHeadEntity.put("FIsPriceExcludeTax", true);//价外税
        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        //循环货品集合，添加金蝶单据体信息
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }

            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //添加单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "SellTotal");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        String unit = (String) unitMap.get(unitName);
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        //金蝶单价为0就是赠品
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", skuCount);//实发数量
                        colMap.put("FTaxPrice", settPrice / skuCount);//含税单价
                        //单价是0就是赠品
                        if (settPrice == 0) {
                            colMap.put("FIsFree", true);//是否赠品
                        } else {
                            colMap.put("FIsFree", false);//是否赠品
                        }

                        colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型

                        double tax = (Double) taxMap.get(goodsNo);//获取税率

                        if (shopName.startsWith("bb")) {
                            colMap.put("FOWNERID", new Document("FNumber", "100"));//货主
                            colMap.put("FKeeperID", new Document("FNumber", "100"));//保管者
                            colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                        } else {
                            colMap.put("FOWNERID", new Document("FNumber", "200"));//货主
                            colMap.put("FKeeperID", new Document("FNumber", "200"));//保管者
                            colMap.put("FStockId", new Document("FNumber", "001"));//仓库
                        }
                        colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                        colMap.put("FEntroynote", goodsMemo);//货品备注
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSALUNITQTY", skuCount);//销售数量
                        colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                        colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                        colMap.put("FOUTCONTROL", false);//控制出库数量
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                        colMap.put("FCheckDelivery", false);//发货检验
                        colMap.put("F_PSUH_QD", new Document("FNumber", qdNo));
                        FEntity.add(colMap);

                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee");//分摊后金额,对应金蝶含税单价
                double skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String unit = (String) unitMap.get(unitName);

                Map<String, Object> colMap = new LinkedHashMap<>();
                //金蝶单价为0就是赠品
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", skuCount);//实发数量
                colMap.put("FTaxPrice", settPrice / skuCount);//含税单价 = 分摊后金额 / 数量
                //单价是0就是赠品
                if (settPrice == 0) {
                    colMap.put("FIsFree", true);//是否赠品
                } else {
                    colMap.put("FIsFree", false);//是否赠品
                }

                colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型

                //colMap.put("FEntryTaxRate", tax);//税率
                if (shopName.startsWith("bb")) {
                    colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                    colMap.put("FKeeperID", new Document("FNumber", "100"));//保管者
                    colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                } else {
                    colMap.put("FOWNERID", new Document("FNumber", "200"));//货主开发销售测试
                    colMap.put("FKeeperID", new Document("FNumber", "200"));//保管者
                    colMap.put("FStockId", new Document("FNumber", "001"));//仓库
                }

                colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                colMap.put("FEntroynote", goodsMemo);//货品备注
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSALUNITQTY", skuCount);//销售数量
                colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                colMap.put("FOUTCONTROL", false);//控制出库数量
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                colMap.put("FCheckDelivery", false);//发货检验
                colMap.put("F_PSUH_QD", new Document("FNumber", qdNo));
                FEntity.add(colMap);
            }
        }

        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", true);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        historyDoc.append("param", payModel);
        String number = "";
        //创建销售出库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_OUTSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            if (e.getMessage().contains("货主组织已关账")) {
                //如果是因为关账原因没有上传成功的需要重新上传,日期为下个月的第一天
                String closeTime = e.getMessage().substring(48, 58);
                Date closeDate = VtuzxUtil.parseDate(closeTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(closeDate);
                calendar.add(Calendar.MONTH, 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);//当月第一天
                Date time = calendar.getTime();
                String firstTime = VtuzxUtil.formatYmdHmsF(time);
                syncKingdeeSaleOutOneAccount(client, data, historyDoc, storeDoc, firstTime);
            } else if (e.getMessage().contains("更新库存不成功!")) {//如果因为库存原因没有上传成功做一个其他入库后再审核
                syncKingdeeOtherInBill(client, data, historyDoc, storeDoc);
                kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            } else if (e.getMessage().contains("库存组织启用日期")) {
                //如果是因为关账原因没有上传成功的需要重新上传,日期为下个月的第一天
                String closeTime = e.getMessage().substring(29, 39);
                System.out.println("");
                Date closeDate = VtuzxUtil.parseDate(closeTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(closeDate);
                calendar.add(Calendar.MONTH, 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);//当月第一天
                Date time = calendar.getTime();
                String firstTime = VtuzxUtil.formatYmdHmsF(time);
                syncKingdeeSaleOutOneAccount(client, data, historyDoc, storeDoc, firstTime);
            } else {
                _logger.info(tradeNo + e.getMessage());
                throw new VtuzxException(e.getMessage());
            }

        }

        return "";
    }


    //野象销售出(因为关账原因重传)
    private String syncKingdeeSaleOutOneAccount(VtuzxKingdeeCloudClient client, VtuzxMap data, Document historyDoc, Document storeDoc, String closeTime) throws Exception {

        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data, "customerName");//客户名称
        String orderTime = VtuzxUtil.getString(historyDoc, "orderTime");//客户名称
        if (VtuzxUtil.isEmpty(customerName)) {
            historyDoc.append("message", "销售单未结算,无法查询到客户信息,请先结算");
            return "销售单未结算,无法查询到客户信息,请先结算";
        }
        //查询客户
        String customerId = getCustomer(customerCode, client, storeDoc, customerName);
        String warehouseName = VtuzxUtil.getString(data, "warehouseName");//仓库名称(吉客云销售渠道)
        String shopName = VtuzxUtil.getString(data, "shopName");//店铺名称
        if ("bb044山东路专卖店-野象".equals(shopName)) {
            shopName = "bb045山东路专卖店-野象";
        }
        //外埠的不要做截取，野象-展示厅不要截取，天猫的不要做截取
        if (shopName.contains("-") && !shopName.contains("外埠") && !shopName.startsWith("bb") && !shopName.contains("展示厅") && !shopName.contains("天猫") && !shopName.startsWith("百年晓芹")) {
            shopName = shopName.substring(0, shopName.indexOf("-"));
        }
        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        //如果查询不到销售渠道
        if (VtuzxUtil.isEmpty(channelDoc)) {
            historyDoc.append("message", "无法查询到销售渠道,请维护渠道");
            return "无法查询到销售渠道,请维护渠道";
        }
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号

        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        double otherFee = VtuzxUtil.getDouble(data, "otherFee");//销售费用
        double discountFee = VtuzxUtil.getDouble(data, "discountFee");//整单优惠
        double couponFee = VtuzxUtil.getDouble(data, "couponFee");//平台补贴(平台优惠)
        String sellerMemo = VtuzxUtil.getString(data, "sellerMemo");//备注(客服备注)
        String buyerMemo = VtuzxUtil.getString(data, "buyerMemo");//(买家备注)客户备注
        String appendMemo = VtuzxUtil.getString(data, "appendMemo");//追加备注
        String onlineTradeNo = VtuzxUtil.getString(data, "onlineTradeNo");//网店订单号
        String seller = VtuzxUtil.getString(data, "seller");//业务员
        String flagNames = VtuzxUtil.getString(data, "flagNames");//标记名称
        String createTime = VtuzxUtil.getString(data, "gmtCreate");//创建日期
//        Date consignTime = VtuzxUtil.getObject(data,"consignTime");//发货日期
        String invoiceStatus = VtuzxUtil.getString(data, "invoiceStatus");//是否开票
        //同步数据时会同步部门,后加的
        String departName = VtuzxUtil.getString(data, "departName");//部门
        String salesManId = "";
        if (!VtuzxUtil.isEmpty(seller)) {
            //如果部门没同步下来的话
            if (VtuzxUtil.isEmpty(departName)) {
                departName = getMainDepartName(seller, storeDoc);//吉客云部门名称
            }
            salesManId = getSellId(seller, client);//金蝶业务员id
        }


        //渠道是爱你商城传金蝶部门为市场部，客户为爱你商城
        if ("爱你商城".equals(shopName)) {
            departName = "市场部";
        } else if (shopName.startsWith("外埠")) {
            departName = shopName;
        }

        if (departName.contains("外埠")) {//如果部门为外埠固定传(因为吉客云和金蝶部门名称没统一)
            departName = "外埠（营销外埠）";
        } else if (departName.contains("网购") || departName.contains("营销三部")) {
            departName = "网购（营销网购）";
        } else if (departName.contains("bb044")) {
            departName = "bb045山东路专卖店";
        } else if (departName.contains("本埠（二）")) {
            departName = "bb047比优特三八广场店";
        } else if (departName.contains("客服部")) {
            departName = "客户信息服务部";
        }
        //查询部门的时候加上禁用状态
        String deliveryDeptId = "";//发货部门id
        String qdNo = "";//
        if (!VtuzxUtil.isEmpty(departName)) {//如果吉客云部门名称不为空，查询金蝶部门id
            //查询发货部门id
            String cond = String.format("FName = '%s' and FForbidStatus ='%s'", departName, "A");
            List<VtuzxMap> bd_department = kingdeeService.query(client, "BD_Department", new VtuzxArrayList<>(
                    "FNumber",//=部门编码
                    "FNAME"//部门
            ), cond);
            if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                deliveryDeptId = (String) bd_department.get(0).get("FNumber");
            }

            //查询客户
            String cusCond = String.format("FName = '%s'", departName);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                    "FNumber",//客户编码
                    "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                    "FNAME"//客户名称
            ), cusCond);
            if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                qdNo = VtuzxUtil.getString(bd_customer.get(0), "F_SXLJ_xsqd.FNUMBER");
            }
        }
        //如果发货部门为空的话不让传
        if (VtuzxUtil.isEmpty(deliveryDeptId)) {
            historyDoc.append("message", "无法查询到部门,请维护");
            return "无法查询到部门,请维护";
        }

        //在同步单据的时候会查询仓库id
        //存在没有仓库的情况,给与提示
        String stockId = VtuzxUtil.getString(data, "stockId");
        if (VtuzxUtil.isEmpty(stockId)) {
            historyDoc.append("message", "没有获取到仓库id,请重新同步单据");
            return "没有获取到仓库id,请重新同步单据";
        }
        //查询客户(门店通过部门查询客户，其他的通过渠道查询)
        String shopCustomerId = "";
        if (shopName.startsWith("bb")) {
            shopCustomerId = getCustomerShopName(client, departName);
        } else {
            //添加门店渠道中的对应关系
            if ("野象考拉店铺".equals(shopName)) {
                shopName = "网易考拉";
            } else if ("野象苏宁超市".equals(shopName)) {
                shopName = "苏宁超市";
            } else if ("客服外卖-代收货款".equals(shopName)) {
                shopName = "客服外卖";
            } else if ("野象-展示厅".equals(shopName)) {
                shopName = "展示厅";
            } else if ("天猫超市-野象".equals(shopName)) {
                shopName = "天猫超市";
            } else if ("客服外卖".equals(shopName)) {
                shopName = "客户信息服务部";
            } else if ("特渠库".equals(shopName)) {
                shopName = "客户信息服务部";
            } else if ("杭州光年有限公司".equals(shopName)) {
                shopName = "光年（杭州）水产品";
            } else if ("天猫旗舰店-野象".equals(shopName)) {
                shopName = "天猫商城";
            } else if ("百年晓芹-拼多多生鲜".equals(shopName)) {
                shopName = "拼多多-生鲜";
            }
            shopCustomerId = getCustomerShopName(client, shopName);
        }
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSCKD01_SYS"));//单据类型 标准销售出库单
        payModel.put("FDate", closeTime);//单据日期
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织

        //如果是外埠的客户还是正常客户
        if ("外埠".equals(channelGroup)) {
            payModel.put("FCustomerID", new Document("FNumber", customerId));//客户
            payModel.put("FReceiverID", new Document("FNumber", customerId));//收货方
            payModel.put("FStockOrgId", new Document("FNumber", "200"));//发货组织(200)
            payModel.put("FSettleID", new Document("FNumber", customerId));//结算方
            payModel.put("FPayerID", new Document("FNumber", customerId));//付款方
        } else {//其他的传渠道信息,渠道是特渠库也传客户
            if ("特渠库".equals(shopName)) {
                payModel.put("FCustomerID", new Document("FNumber", customerId));//客户
                payModel.put("FReceiverID", new Document("FNumber", customerId));//收货方
                payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织(200)
                payModel.put("FSettleID", new Document("FNumber", customerId));//结算方
                payModel.put("FPayerID", new Document("FNumber", customerId));//付款方
            } else {
                payModel.put("FCustomerID", new Document("FNumber", shopCustomerId));//渠道
                payModel.put("FReceiverID", new Document("FNumber", shopCustomerId));//收货方
                if (shopName.startsWith("bb")) {
                    payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织(200)
                } else {
                    payModel.put("FStockOrgId", new Document("FNumber", "200"));//发货组织(200)
                }
//                payModel.put("FStockOrgId", new Document("FNumber", "200"));//发货组织(200)
                payModel.put("FSettleID", new Document("FNumber", shopCustomerId));//结算方
                payModel.put("FPayerID", new Document("FNumber", shopCustomerId));//付款方
            }

        }

        payModel.put("FDeliveryDeptID", new Document("FNumber", "01"));//发货部门
        payModel.put("FSaleDeptID", new Document("FNumber", deliveryDeptId));//销售部门
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FCDateOffsetValue", 0);
        payModel.put("FIsTotalServiceOrCost", false);//整单服务或费用
        payModel.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
        payModel.put("F_ora_disFee", discountFee);//整单优惠
        payModel.put("F_ora_appendMemo", appendMemo);//追加备注
        payModel.put("F_ora_saleFee", otherFee);//销售费用
//        payModel.put("F_ora_kefuMemo",sellerMemo);//客服备注
        payModel.put("F_ora_kehuMemo", buyerMemo);//客户备注
        payModel.put("F_ora_lineTradeNo", onlineTradeNo);//网店订单号
        payModel.put("F_PSUH_biaoji", flagNames);//标记
        payModel.put("F_PSUH_couponFee", couponFee);//平台补贴
        payModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        payModel.put("F_PSUH_DPMC", shopName);//店铺名称
        payModel.put("F_PSUH_KH", customerName);//客户名称
        payModel.put("F_SXLJ_JKYKHBH", customerCode);//客户编号
        //如果是3的话为开票成功，其他为未开票
        if ("3".equals(invoiceStatus)) {
            payModel.put("F_PSUH_SFKP", true);//是否开票
        } else {
            payModel.put("F_PSUH_SFKP", false);//是否开票
        }

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FIsIncludedTax", true);//是否含税
        SubHeadEntity.put("FLocalCurrID", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        SubHeadEntity.put("FIsPriceExcludeTax", true);//价外税
        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        List<String> materialNoList = new ArrayList<>();//物料编码集合,为了查询税率
        //循环货品集合，添加金蝶单据体信息
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }

            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //添加单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "SellTotal");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        String unit = (String) unitMap.get(unitName);
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        //金蝶单价为0就是赠品
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", skuCount);//实发数量
                        colMap.put("FTaxPrice", settPrice / skuCount);//含税单价
                        //单价是0就是赠品
                        if (settPrice == 0) {
                            colMap.put("FIsFree", true);//是否赠品
                        } else {
                            colMap.put("FIsFree", false);//是否赠品
                        }

                        colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型

                        double tax = (Double) taxMap.get(goodsNo);//获取税率

                        if (shopName.startsWith("bb")) {
                            colMap.put("FOWNERID", new Document("FNumber", "100"));//货主
                            colMap.put("FKeeperID", new Document("FNumber", "100"));//保管者
                            colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                        } else {
                            colMap.put("FOWNERID", new Document("FNumber", "200"));//货主
                            colMap.put("FKeeperID", new Document("FNumber", "200"));//保管者
                            colMap.put("FStockId", new Document("FNumber", "001"));//仓库
                        }
                        colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                        colMap.put("FEntroynote", goodsMemo);//货品备注
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSALUNITQTY", skuCount);//销售数量
                        colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                        colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                        colMap.put("FOUTCONTROL", false);//控制出库数量
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                        colMap.put("FCheckDelivery", false);//发货检验
                        colMap.put("F_PSUH_QD", new Document("FNumber", qdNo));//发货检验
                        FEntity.add(colMap);

                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee");//分摊后金额,对应金蝶含税单价
                double skuCount = VtuzxUtil.getDouble(doc, "SellCount");
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String unit = (String) unitMap.get(unitName);

                Map<String, Object> colMap = new LinkedHashMap<>();
                //金蝶单价为0就是赠品
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", skuCount);//实发数量
                colMap.put("FTaxPrice", settPrice / skuCount);//含税单价 = 分摊后金额 / 数量
                //单价是0就是赠品
                if (settPrice == 0) {
                    colMap.put("FIsFree", true);//是否赠品
                } else {
                    colMap.put("FIsFree", false);//是否赠品
                }

                colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型

                //colMap.put("FEntryTaxRate", tax);//税率
                if (shopName.startsWith("bb")) {
                    colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                    colMap.put("FKeeperID", new Document("FNumber", "100"));//保管者
                    colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                } else {
                    colMap.put("FOWNERID", new Document("FNumber", "200"));//货主开发销售测试
                    colMap.put("FKeeperID", new Document("FNumber", "200"));//保管者
                    colMap.put("FStockId", new Document("FNumber", "001"));//仓库
                }

                colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                colMap.put("FEntroynote", goodsMemo);//货品备注
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSALUNITQTY", skuCount);//销售数量
                colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                colMap.put("FOUTCONTROL", false);//控制出库数量
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                colMap.put("FCheckDelivery", false);//发货检验
                colMap.put("F_PSUH_QD", new Document("FNumber", qdNo));//发货检验
                FEntity.add(colMap);
            }
        }

        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", true);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        historyDoc.append("param", payModel);
        String number = "";
        //创建销售出库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_OUTSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            if (e.getMessage().contains("更新库存不成功!")) {//如果因为库存原因没有上传成功做一个其他入库后再审核
                syncKingdeeOtherInBill(client, data, historyDoc, storeDoc);
                kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            } else {
                _logger.info(tradeNo + e.getMessage());
                throw new VtuzxException(e.getMessage());
            }

        }

        return "";
    }

    /**
     * 整理野象销售出库单的物料
     *
     * @param goodsList
     * @param tradeOrderAssemblyGoodsDtoList
     * @param materialNoList
     * @return
     */
    private Map<String, Object> arrangeMaterial(List<Map<String, Object>> goodsList, List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList, List<String> materialNoList) {
        Map<String, Object> materialMap = new HashMap<>();
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        if (!materialNoList.contains(goodsNo)) {
                            materialNoList.add(goodsNo);
                        }
                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                if (!materialNoList.contains(goodsNo)) {
                    materialNoList.add(goodsNo);
                }
            }
        }
        return materialMap;
    }


    //金蝶调拨
    private void syncKingdeeAllocation(VtuzxKingdeeCloudClient client, List<Document> dataList) throws Exception {

        for (Document data : dataList) {
            String allocationNo = VtuzxUtil.getString(data, "allocateNo");
            Map<String, Object> param = new LinkedHashMap<>();
            List<Map<String, Object>> stockAllocateDetailViews = VtuzxUtil.getObject(data, "stockAllocateDetailViews");
            List<Map<String, Object>> stockTransferEntryList = new ArrayList<>();//存放单据体数据
            Map<String, Object> model = new LinkedHashMap<>();
            model.put("FID", 0);//实体主键
            model.put("FBillTypeID", new VtuzxMap("FNUMBER", "ZJDB01_SYS"));//单据类型
            model.put("FBizType", "NORMAL");//业务类型
            model.put("FTransferDirect", "GENERAL");//调拨方向
            model.put("FTransferBizType", "InnerOrgTransfer");//调拨类型
            model.put("FSettleOrgId", new VtuzxMap("FNumber", "100"));//结算组织
            model.put("FSaleOrgId", new VtuzxMap("FNumber", "100"));//销售组织
            model.put("FStockOutOrgId", new VtuzxMap("FNumber", "100"));//调出库存组织
            model.put("FOwnerTypeOutIdHead", "BD_OwnerOrg");//调出货主类型
            model.put("FOwnerOutIdHead", new VtuzxMap("FNumber", "100"));//调出货主
            model.put("FStockOrgId", new VtuzxMap("FNumber", "100"));//调入库存组织
            model.put("FIsIncludedTax", true);//是否含税
            model.put("FIsPriceExcludeTax", true);//价外税
            model.put("FExchangeTypeId", new VtuzxMap("FNUMBER", "HLTX01_SYS"));//汇率类型
            model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//调入货主类型
            model.put("FSETTLECURRID", new VtuzxMap("FNumber", "PRE001"));
            model.put("FExchangeRate", 1.0);
            model.put("FOwnerIdHead", new VtuzxMap("FNumber", "100"));
            model.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));
            model.put("FBaseCurrId", new VtuzxMap("FNumber", "PRE001"));
            model.put("FWriteOffConsign", false);//冲减普通寄售调拔单结算数量

            //单据体数据
            for (Map<String, Object> stockAllocateDetailView : stockAllocateDetailViews) {
                String goodsNo = VtuzxUtil.getString(stockAllocateDetailView, "goodsNo");
                double skuCount = VtuzxUtil.getDouble(stockAllocateDetailView, "skuCount");
                //判断是否启用批号
                String floatCond = String.format("FNumber = '%s'", goodsNo);
                List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FIsBatchManage",
                        "FMATERIALID",
                        "FBaseUnitId"
                ), floatCond);
                //获取单位编码
                boolean flag = true;
                String materialId = "";//物料编码id
                String unitId = "";//单位id
                if (bd_Material != null && bd_Material.size() > 0) {
                    flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                    materialId = bd_Material.get(0).getString("FMATERIALID");
                    unitId = bd_Material.get(0).getString("FBaseUnitId");
                }
                //查询单位编码，
                String cond = String.format("FUNITID  = '%s'", unitId);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",
                        "FNAME"
                ), cond);
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }


                String inventoryCond = String.format("FMaterialId = '%s' and FBaseQty > '%d'", materialId, 0);
                List<VtuzxMap> bd_inventory = kingdeeService.query(client, "STK_Inventory", new VtuzxArrayList<>(
                        "FStockId",
                        "FMaterialId",
                        "FLot",
                        "FBaseQty"
                ), inventoryCond);

                List<VtuzxMap> colMapList = new ArrayList<>();
                for (VtuzxMap inventoryMap : bd_inventory) {
                    double residue = VtuzxUtil.getDouble(inventoryMap, "FBaseQty");
                    if (residue >= skuCount) {
                        inventoryMap.replace("FBaseQty", skuCount);
                        colMapList.add(inventoryMap);
                        break;
                    } else {//如果数量不够扣的话
                        skuCount -= residue;
                        colMapList.add(inventoryMap);
                    }
                }
                //循环添加但具体数据

                for (VtuzxMap map : colMapList) {
                    String stockId = "";//仓库编码
                    String stockNoId = VtuzxUtil.getString(map, "FStockId");//仓库Id
                    String flotNoId = VtuzxUtil.getString(map, "FLot");//批号id
                    double count = VtuzxUtil.getDouble(map, "FBaseQty");
                    //查询仓库
                    String stockCond = String.format("FStockId = '%s'", stockNoId);
                    List<VtuzxMap> bd_stock = kingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
                            "FNumber"
                    ), stockCond);
                    if (bd_stock != null && bd_stock.size() > 0) {
                        stockId = bd_stock.get(0).getString("FNumber");
                    }

                    Map<String, Object> stockTransferEntry = new LinkedHashMap<>();
                    stockTransferEntry.put("FMaterialId", new VtuzxMap("FNumber", goodsNo));
                    stockTransferEntry.put("FUnitID", new VtuzxMap("FNumber", unit));
                    stockTransferEntry.put("FQty", skuCount);
                    String batchNo = "";
                    if (flag) {
                        String batchCond = String.format("FLOTID  = '%s'", flotNoId);
                        List<VtuzxMap> bd_batch = kingdeeService.query(client, "BD_BatchMainFile", new VtuzxArrayList<>(
                                "FNumber"
                        ), batchCond);

                        if (bd_batch != null && bd_batch.size() > 0) {
                            batchNo = bd_batch.get(0).getString("FNumber");
                        }

                        stockTransferEntry.put("FLot", new VtuzxMap("FNumber", batchNo));
                    }

                    stockTransferEntry.put("FSrcStockId", new VtuzxMap("FNumber", stockId));//调出仓库
                    stockTransferEntry.put("FDestStockId", new VtuzxMap("FNumber", "CK002"));//调入仓库
                    stockTransferEntry.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
                    stockTransferEntry.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
                    stockTransferEntry.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
                    stockTransferEntry.put("FOwnerTypeOutId", "BD_OwnerOrg");
                    stockTransferEntry.put("FOwnerOutId", new VtuzxMap("FNumber", "100"));
                    stockTransferEntry.put("FOwnerTypeId", "BD_OwnerOrg");
                    stockTransferEntry.put("FOwnerId", new VtuzxMap("FNumber", "100"));
                    stockTransferEntry.put("FBaseUnitId", new VtuzxMap("FNumber", unit));
                    stockTransferEntry.put("FBaseQty", count);
                    stockTransferEntry.put("FISFREE", false);
                    stockTransferEntry.put("FKeeperTypeId", "BD_KeeperOrg");
                    stockTransferEntry.put("FKeeperId", new VtuzxMap("FNumber", "100"));
                    stockTransferEntry.put("FKeeperTypeOutId", "BD_KeeperOrg");
                    stockTransferEntry.put("FKeeperOutId", new VtuzxMap("FNumber", "100"));
                    stockTransferEntry.put("FDestLot", new VtuzxMap("FNumber", "LS"));
                    stockTransferEntry.put("FDestMaterialId", new VtuzxMap("FNumber", goodsNo));
                    stockTransferEntry.put("FSaleUnitId", new VtuzxMap("FNumber", unit));
                    stockTransferEntry.put("FSaleQty", count);
                    stockTransferEntry.put("FSalBaseQty", count);
                    stockTransferEntry.put("FPriceUnitID", new VtuzxMap("FNumber", unit));
                    stockTransferEntry.put("FPriceQty", count);
                    stockTransferEntry.put("FPriceBaseQty", count);
                    stockTransferEntry.put("FTransReserveLink", false);
                    stockTransferEntry.put("FCheckDelivery", false);
                    stockTransferEntryList.add(stockTransferEntry);
                }

            }
            model.put("FBillEntry", stockTransferEntryList);
            param.put("NeedUpDateFields", new ArrayList<>());
            param.put("NeedReturnFields", new ArrayList<>());
            param.put("IsDeleteEntry", true);
            param.put("SubSystemId", "");
            param.put("IsVerifyBaseDataField", false);
            param.put("IsEntryBatchFill", true);
            param.put("ValidateFlag", true);
            param.put("NumberSearch", true);
            param.put("IsAutoAdjustField", false);
            param.put("InterationFlags", "");
            param.put("IgnoreInterationFlag", "");
            param.put("IsControlPrecision", false);
            param.put("ValidateRepeatJson", false);
            param.put("Model", model);
            try {
                List<VtuzxMap> transferList = kingdeeService.save(client, "STK_TransferDirect", param);
                VtuzxMap transferMap = transferList.get(0);
                String number = VtuzxUtil.getString(transferMap, "Number");
                kingdeeService.submit(client, "STK_TransferDirect", "0", number);
                kingdeeService.audit(client, "STK_TransferDirect", "0", number, "STK_InvCheckResult");
                String _id = VtuzxUtil.getString(data, "_id");
                jikeyunAllocationDao.updateById(_id, new Document("isUpload", "yes"));

            } catch (Exception e) {
                _logger.info(e.getMessage());
            }

        }
    }

    //晓芹销售出(公司间结算销售类型)
    private void suncKingdeeSaleOutOne(VtuzxKingdeeCloudClient client, Document data, Document historyDoc) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        //查询销售单获取客户信息

        Long gmtCreate = VtuzxUtil.getObject(data, "gmtCreate");//创建时间
        //通过销售订单查询客户
        String sourceBillNo = VtuzxUtil.getString(data, "sourceBillNo");//销售单号
        VtuzxMap saleMap = jiKeYunApiService.getSaleBill(storeDoc,
                new VtuzxMap()
                        .append("tradeNo", sourceBillNo)
                        .append("pageSize", 50)
                        .append("pageIndex", 0)
                        .append("fields", "shopName,shopId,customerCode"));

        Map<String, Object> tradeResult = VtuzxUtil.getObject(saleMap, "result");

        String tradeString = VtuzxUtil.getString(tradeResult, "data");
        Map<String, Object> tradeData = JSON.parseObject(tradeString, new TypeReference<HashMap<String, Object>>() {
        });
        JSONArray jsonArray = VtuzxUtil.getObject(tradeData, "Trades");
        JSONObject jsonTrades = (JSONObject) jsonArray.get(0);
        Map<String, Object> tradeMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : jsonTrades.entrySet()) {
            tradeMap.put(entry.getKey(), entry.getValue());
        }
        String customerCode = VtuzxUtil.getString(tradeMap, "CustomerCode");
        String customerId = "";//传金蝶的客户编号
        //先判断客户是否加密
        VtuzxMap customerMap = jiKeYunApiService.customerList(storeDoc,
                new VtuzxMap("customerCode", customerCode));//客户编号

        Map<String, Object> customerResult = VtuzxUtil.getObject(customerMap, "result");
        List<Map<String, Object>> customerData = VtuzxUtil.getObject(customerResult, "data");
        Map<String, Object> customerDoc = customerData.get(0);

        String nickName = VtuzxUtil.getString(customerDoc, "nickname");
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(nickName);
        if ((!m.find() && nickName.length() > 8) || VtuzxUtil.isEmpty(nickName)) {//说明是加密的,查询销售渠道，传渠道编号
            String shopName = VtuzxUtil.getString(tradeMap, "ShopName");//销售渠道
//            VtuzxMap getSales = jiKeYunApiService.getSales(storeDoc,
//                    new VtuzxMap("name", shopName)
//                            .append("pageSize", 1)
//                            .append("pageIndex", 0));
//            Map<String, Object> channelResult = VtuzxUtil.getObject(getSales, "result");
//            Map<String, Object> channelData = VtuzxUtil.getObject(channelResult, "data");
//            List<Map<String, Object>> salesChannelInfo = VtuzxUtil.getObject(channelData, "salesChannelInfo");
//            customerId = VtuzxUtil.getString(salesChannelInfo.get(0),"channelCode");
            //查询客户
            String cond = String.format("FNumber = '%s'", shopName);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                    "FNumber",//客户编码
                    "FNAME"//客户名称
            ), cond);
            if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                customerId = customerCode;
            } else {//没有的话做新增
                String telephone = VtuzxUtil.getString(customerMap, "phone");
                Map<String, Object> model = new LinkedHashMap<>();
                model.put("FCUSTID", 0);
                model.put("FCreateOrgId", new Document("FNumber", "100"));
                model.put("FNumber", customerCode);//客户编码
                model.put("FUseOrgId", new Document("FNumber", "100"));//使用组织
                model.put("FName", nickName);//客户姓名
                model.put("FCOUNTRY", new Document("FNumber", "China"));
                model.put("FTEL", telephone);
                model.put("FINVOICETITLE", nickName);//发票抬头
                model.put("FIsGroup", false);//集团客户
                model.put("FIsDefPayer", false);//默认付款方
                model.put("FCustTypeId", new Document("FNumber", "KHLB001_SYS"));//客户类别
                //TODO
                model.put("FGroup", new Document("FNumber", "01"));//客户分组
                model.put("FTRADINGCURRID", new Document("FNumber", "PRE001"));//结算币别
                model.put("FInvoiceType", "1");//发票类型
                model.put("FTaxType", new Document("FNumber", "SFL02_SYS"));//税分类
                model.put("FPriority", "1");//客户优先级
                model.put("FTaxRate", new Document("FNumber", "SL02_SYS"));//默认税率
                model.put("FISCREDITCHECK", true);//启用信用管理
                model.put("FIsTrade", true);//是否交易客户
                model.put("FUncheckExpectQty", false);//不校验可发量
                Map<String, Object> customerext = new LinkedHashMap<>();//商务信息
                customerext.put("FEnableSL", false);//启用商联在线
                customerext.put("FALLOWJOINZHJ", false);//允许对接智慧订货
                model.put("FT_BD_CUSTOMEREXT", customerext);


                Map<String, Object> kneeParam = new LinkedHashMap<>();
                kneeParam.put("NeedUpDateFields", new ArrayList<>());
                kneeParam.put("NeedReturnFields", new ArrayList<>());
                kneeParam.put("IsDeleteEntry", true);
                kneeParam.put("SubSystemId", "");
                kneeParam.put("IsVerifyBaseDataField", true);
                kneeParam.put("IsEntryBatchFill", false);
                kneeParam.put("ValidateFlag", true);
                kneeParam.put("NumberSearch", true);
                kneeParam.put("IsAutoAdjustField", false);
                kneeParam.put("InterationFlags", "");
                kneeParam.put("IgnoreInterationFlag", "");
                kneeParam.put("IsControlPrecision", false);
                kneeParam.put("ValidateRepeatJson", false);
                kneeParam.put("Model", model);
                try {
                    List<VtuzxMap> customerList = kingdeeService.save(client, "BD_Customer", kneeParam);
                    VtuzxMap kingdeeCustomerMap = customerList.get(0);
                    String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
                    kingdeeService.submit(client, "BD_Customer", "0", number);
                    kingdeeService.audit(client, "BD_Customer", "0", number, "STK_InvCheckResult");
                    customerId = customerCode;
                } catch (Exception e) {
                    _logger.info(e.getMessage());
                }
            }

        } else {//没加密先去金蝶查询是否存在，不存在做新增
            //查询客户
            String cond = String.format("FNumber = '%s'", customerCode);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                    "FNumber",//客户编码
                    "FNAME"//客户名称
            ), cond);
            if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                customerId = customerCode;
            } else {//没有的话做新增
                String telephone = VtuzxUtil.getString(customerMap, "phone");
                Map<String, Object> model = new LinkedHashMap<>();
                model.put("FCUSTID", 0);
                model.put("FCreateOrgId", new Document("FNumber", "100"));
                model.put("FNumber", customerCode);//客户编码
                model.put("FUseOrgId", new Document("FNumber", "100"));//使用组织
                model.put("FName", nickName);//客户姓名
                model.put("FCOUNTRY", new Document("FNumber", "China"));
                model.put("FTEL", telephone);
                model.put("FINVOICETITLE", nickName);//发票抬头
                model.put("FIsGroup", false);//集团客户
                model.put("FIsDefPayer", false);//默认付款方
                model.put("FCustTypeId", new Document("FNumber", "KHLB001_SYS"));//客户类别
                //TODO
                model.put("FGroup", new Document("FNumber", "01"));//客户分组
                model.put("FTRADINGCURRID", new Document("FNumber", "PRE001"));//结算币别
                model.put("FInvoiceType", "1");//发票类型
                model.put("FTaxType", new Document("FNumber", "SFL02_SYS"));//税分类
                model.put("FPriority", "1");//客户优先级
                model.put("FTaxRate", new Document("FNumber", "SL02_SYS"));//默认税率
                model.put("FISCREDITCHECK", true);//启用信用管理
                model.put("FIsTrade", true);//是否交易客户
                model.put("FUncheckExpectQty", false);//不校验可发量
                Map<String, Object> customerext = new LinkedHashMap<>();//商务信息
                customerext.put("FEnableSL", false);//启用商联在线
                customerext.put("FALLOWJOINZHJ", false);//允许对接智慧订货
                model.put("FT_BD_CUSTOMEREXT", customerext);


                Map<String, Object> kneeParam = new LinkedHashMap<>();
                kneeParam.put("NeedUpDateFields", new ArrayList<>());
                kneeParam.put("NeedReturnFields", new ArrayList<>());
                kneeParam.put("IsDeleteEntry", true);
                kneeParam.put("SubSystemId", "");
                kneeParam.put("IsVerifyBaseDataField", true);
                kneeParam.put("IsEntryBatchFill", false);
                kneeParam.put("ValidateFlag", true);
                kneeParam.put("NumberSearch", true);
                kneeParam.put("IsAutoAdjustField", false);
                kneeParam.put("InterationFlags", "");
                kneeParam.put("IgnoreInterationFlag", "");
                kneeParam.put("IsControlPrecision", false);
                kneeParam.put("ValidateRepeatJson", false);
                kneeParam.put("Model", model);
                try {
                    List<VtuzxMap> customerList = kingdeeService.save(client, "BD_Customer", kneeParam);
                    VtuzxMap kingdeeCustomerMap = customerList.get(0);
                    String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
                    kingdeeService.submit(client, "BD_Customer", "0", number);
                    kingdeeService.audit(client, "BD_Customer", "0", number, "STK_InvCheckResult");
                    customerId = customerCode;
                } catch (Exception e) {
                    _logger.info(e.getMessage());
                }
            }
        }

        String departMentId = "";//金蝶部门id
        String stockId = "";//仓库id

        String orderNo = VtuzxUtil.getString(data, "orderNo");
        String goodsdocNo = VtuzxUtil.getString(data, "goodsdocNo");//销售出库单号
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSCKD01_SYS"));//单据类型 标准销售出库单
        payModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date(gmtCreate)));//单据日期
//        payModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));//单据日期
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        payModel.put("FCustomerID", new Document("FNumber", customerId));//客户 固定野象
        payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织
        payModel.put("FDeliveryDeptID", new Document("FNumber", departMentId));//发货部门
        payModel.put("FReceiverID", new Document("FNumber", customerId));//收货方 固定野象
        payModel.put("FSettleID", new Document("FNumber", customerId));//结算方 固定野象
        payModel.put("FPayerID", new Document("FNumber", customerId));//付款方 固定野象
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务或费用
        payModel.put("F_XSCK_JKYDJH", orderNo);

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FIsIncludedTax", true);//是否含税
        SubHeadEntity.put("FLocalCurrID", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        SubHeadEntity.put("FIsPriceExcludeTax", true);//价外税
        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据


        //查询出库单获取出库信息(唯一码出库)
        if (!VtuzxUtil.isEmpty(goodsdocNo)) {
            List<String> serialNoList = new ArrayList<>();//存放唯一码集合
            List<Document> serialList = new ArrayList<>();//唯一码和单价等相关信息集合

            //查询极客云公出库单
            VtuzxMap param = new VtuzxMap();
            param.append("pageSize", 1)
                    .append("selelctFields", "recId,goodsdocNo,inOutDate,gmtCreate,inouttypeName,vendCustomerName,warehouseCode,warehouseName,comment,companyId,companyName,inOutReason,goodsDocDetailList.recId,goodsDocDetailList.goodsNo,goodsDocDetailList.goodsName,goodsDocDetailList.goodsName,goodsDocDetailList.skuId,goodsDocDetailList.skuName,goodsDocDetailList.skuBarcode,goodsDocDetailList.unitName,goodsDocDetailList.quantity,goodsDocDetailList.serialNo,goodsDocDetailList.estPrice,goodsDocDetailList.taxRate")
                    .append("goodsdocNo", goodsdocNo)
                    .append("pageIndex", 0);
            VtuzxMap stotrageDoc = jiKeYunApiService.getStorageOut(storeDoc, param);
            Map<String, Object> outresult = VtuzxUtil.getObject(stotrageDoc, "result");
            List<Map<String, Object>> outdata = VtuzxUtil.getObject(outresult, "data");
            Map<String, Object> outDoc = outdata.get(0);
            List<Map<String, Object>> goodsDocDetailList = VtuzxUtil.getObject(outDoc, "goodsDocDetailList");//出库货品信息


            for (Map<String, Object> goodsMap : goodsDocDetailList) {
                String jackSerialNo = VtuzxUtil.getString(goodsMap, "serialNo");
                String goodsNo = VtuzxUtil.getString(goodsMap, "goodsNo");
                String unitName = VtuzxUtil.getString(goodsMap, "unitName");
                double estPrice = VtuzxUtil.getDouble(goodsMap, "estPrice");//含税单价
                double taxRate = VtuzxUtil.getDouble(goodsMap, "taxRate");//税率
                double quantity = VtuzxUtil.getDouble(goodsMap, "quantity");//出库数量

                String serialNo = "";
                if (!VtuzxUtil.isEmpty(jackSerialNo)) {//是唯一码出库
                    if (jackSerialNo.startsWith("HTTP://ZS")) {
                        StringBuilder sb = new StringBuilder(jackSerialNo.toLowerCase());
                        sb.setCharAt(49, 'Z');
                        sb.setCharAt(44, 'C');
                        serialNo = sb.toString();
                        serialNoList.add(serialNo);
                        Document document = new Document();
                        document.append("estPrice", estPrice)
                                .append("taxRate", taxRate)
                                .append("unit", unitName)
                                .append("serialNo", serialNo);
                        serialList.add(document);
                    }

                    //查询唯一码所在仓库
//                    Document traceabilityDoc = traceabilityCodeDetailDao.findOne(Criteria.where("traceabilityCode").is(serialNo));
//                    String boxNo = VtuzxUtil.getString(traceabilityDoc,"boxNo");
//                    Document prdInDetailBoxDoc  = prdInDetailBoxDao.findOne(Criteria.where("boxNo").is(boxNo));
//                    String billNo = VtuzxUtil.getString(prdInDetailBoxDoc,"billNo");
//                    Document prdInDetailDoc = prdInDetailDao.findOne(Criteria.where("billNo").is(billNo));
//                    String outstockId = VtuzxUtil.getString(prdInDetailDoc,"stockNo");//仓库编码
//                    String batchNo = VtuzxUtil.getString(prdInDetailDoc,"batchNo");
//                    Map<String, Object> colMap = new LinkedHashMap<>();
//                    colMap.put("FRowType", "Standard");//产品类型
//                    colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
//                    colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
//                    colMap.put("FRealQty", 1);//实发数量
//                    colMap.put("FTaxPrice", estPrice);//含税单价
//                    colMap.put("FIsFree", false);//是否赠品
//                    colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
//                    colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
//                    colMap.put("FLot", new Document("FNumber", batchNo));//批号
//                    colMap.put("FEntryTaxRate", taxRate);//税率
//                    colMap.put("FStockId", new Document("FNumber", outstockId));//仓库
//                    colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
//                    colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
//                    colMap.put("FSALUNITQTY", 1);//销售数量
//                    colMap.put("FSALBASEQTY", 1);//销售基本数量
//                    colMap.put("FPRICEBASEQTY", 1);//计价基本数量
//                    colMap.put("FOUTCONTROL", false);//控制出库数量
//                    colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
//                    colMap.put("FARNOTJOINQTY", 1);//未关联应付数量（计价单位
//                    colMap.put("FCheckDelivery", false);//发货检验
//                    FEntity.add(colMap);
                } else {//不是唯一码出库
                    //查询单位编码，直接传文字无效
                    String cond = String.format("Fname = '%s'", unitName);
                    List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                            "FNumber"
                    ), cond);
                    //获取单位编码
                    String unit = "";
                    if (bd_customer != null && bd_customer.size() > 0) {
                        unit = bd_customer.get(0).getString("FNumber");
                    }

                    //判断是否启用批号(单位编码)
                    String floatCond = String.format("FNumber = '%s'", goodsNo);
                    List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                            "FIsBatchManage",
                            "FMATERIALID"
                    ), floatCond);

                    boolean flag = true;
                    String materialId = "";//物料编码id
                    if (bd_Material != null && bd_Material.size() > 0) {
                        flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                        materialId = bd_Material.get(0).getString("FMATERIALID");
                    }
                    //查询即时库存取物料仓库信息
                    String inventoryCond = String.format("FMaterialId = '%s' and FBaseQty > '%d'", materialId, 0);
                    List<VtuzxMap> bd_inventory = kingdeeService.query(client, "STK_Inventory", new VtuzxArrayList<>(
                            "FStockId",
                            "FMaterialId",
                            "FLot",
                            "FBaseQty"
                    ), inventoryCond);

                    List<VtuzxMap> colMapList = new ArrayList<>();
                    for (VtuzxMap inventoryMap : bd_inventory) {
                        double residue = VtuzxUtil.getDouble(inventoryMap, "FBaseQty");
                        if (residue >= quantity) {
                            inventoryMap.replace("FBaseQty", quantity);
                            colMapList.add(inventoryMap);
                            break;
                        } else {//如果数量不够扣的话
                            quantity -= residue;
                            colMapList.add(inventoryMap);
                        }
                    }
                    //循环添加但具体数据
                    for (VtuzxMap map : colMapList) {
                        String stockNoId = VtuzxUtil.getString(map, "FStockId");//仓库Id
                        String flotNoId = VtuzxUtil.getString(map, "FLot");//批号id
                        double count = VtuzxUtil.getDouble(map, "FBaseQty");
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");//产品类型
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", count);//实发数量
                        colMap.put("FTaxPrice", estPrice);//含税单价
                        colMap.put("FIsFree", false);//是否赠品
                        colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                        colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                        String batchNo = "";
                        if (flag) {
                            String batchCond = String.format("FLOTID  = '%s'", flotNoId);
                            List<VtuzxMap> bd_batch = kingdeeService.query(client, "BD_BatchMainFile", new VtuzxArrayList<>(
                                    "FNumber"
                            ), batchCond);
                            if (bd_batch != null && bd_batch.size() > 0) {
                                batchNo = bd_batch.get(0).getString("FNumber");
                            }
                            colMap.put("FLot", new Document("FNumber", batchNo));//批号
                        }
                        colMap.put("FEntryTaxRate", taxRate);//税率
                        //查询仓库
                        String stockCond = String.format("FStockId = '%s'", stockNoId);
                        List<VtuzxMap> bd_stock = kingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
                                "FNumber"
                        ), stockCond);
                        if (bd_stock != null && bd_stock.size() > 0) {
                            stockId = bd_stock.get(0).getString("FNumber");
                        }
                        colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                        colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSALUNITQTY", count);//销售数量
                        colMap.put("FSALBASEQTY", count);//销售基本数量
                        colMap.put("FPRICEBASEQTY", count);//计价基本数量
                        colMap.put("FOUTCONTROL", false);//控制出库数量
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", count);//未关联应付数量（计价单位
                        colMap.put("FCheckDelivery", false);//发货检验
                        FEntity.add(colMap);
                    }
                }
            }
            //去及时库存查询仓库和批次等信息，先查询内层表
            List<ObjectId> inventoryIdList = new ArrayList<>();
            List<Document> inventoryDetailList = new ArrayList<>();
            Iterator<Document> inventoryDetailItr = inventoryDetailDao.findList(Criteria.where("traceBack.traceBackNo").in(serialNoList), null, 0, 0);
            while (inventoryDetailItr.hasNext()) {
                Document detailDoc = inventoryDetailItr.next();
                ObjectId _inventoryId = VtuzxUtil.getObject(detailDoc, "_inventoryId");
                if (!inventoryIdList.contains(_inventoryId)) {
                    inventoryIdList.add(_inventoryId);
                }
                inventoryDetailList.add(detailDoc);
            }
            //去外层表查询批号信息
            List<Document> inventoryList = new ArrayList<>();
            Iterator<Document> inventoryItr = inventoryDao.findList(Criteria.where("_id").in(inventoryIdList), null, 0, 0);
            while (inventoryItr.hasNext()) {
                Document inventoryDoc = inventoryItr.next();
                inventoryList.add(inventoryDoc);
            }
            //把批号信息添加到内层
            for (Document document : inventoryDetailList) {
                ObjectId _inventoryId = VtuzxUtil.getObject(document, "_inventoryId");
                for (Document doc : inventoryList) {
                    ObjectId _id = VtuzxUtil.getObject(doc, "_id");
                    if (_inventoryId.equals(_id)) {
                        String batchNo = VtuzxUtil.getString(doc, "batchNo");
                        String materialNo = VtuzxUtil.getString(doc, "materialNo");
                        document.append("batchNo", batchNo)
                                .append("materialNo", materialNo);
                        break;
                    }
                }
            }

            Map<String, Document> dataMap = new HashMap<>();//k:物料 + 批次 + 仓库 v:唯一码相关信息(数量，单价，税率)
            //把数据整理到map集合里
            for (Document document : serialList) {
                String serialNo = VtuzxUtil.getString(document, "serialNo");
                for (Document doc : inventoryDetailList) {//及时库存
                    List<Document> traceBack = VtuzxUtil.getObject(doc, "traceBack");
                    for (Document serialDoc : traceBack) {
                        String traceBackNo = VtuzxUtil.getString(serialDoc, "traceBackNo");
                        if (serialNo.equals(traceBackNo)) {
                            String materialNo = VtuzxUtil.getString(doc, "materialNo");
                            String batchNo = VtuzxUtil.getString(doc, "batchNo");
                            String stockNo = VtuzxUtil.getString(doc, "stockNo");
                            Document serialData = dataMap.get(materialNo + "_" + batchNo + "_" + stockNo);
                            if (VtuzxUtil.isEmpty(serialData)) {//如果从map集合中获取的数据为空
                                Document serial = new Document();
                                serial.append("count", 1)
                                        .append("unit", VtuzxUtil.getString(document, "unit"))
                                        .append("estPrice", VtuzxUtil.getDouble(document, "estPrice"))//含税单价
                                        .append("taxRate", VtuzxUtil.getDouble(document, "taxRate"));//税率
                                dataMap.put(materialNo + "_" + batchNo + "_" + stockNo, serial);
                                break;
                            } else {//如果有数据的话,把数量改一下
                                double count = VtuzxUtil.getDouble(serialData, "count");
                                serialData.replace("count", count + 1);
                                dataMap.put(materialNo + "_" + batchNo + "_" + stockNo, serialData);
                                break;
                            }

                        }
                    }
                }
            }
            //循环map集合向金蝶添加数据
            for (Map.Entry entry : dataMap.entrySet()) {
                String key = (String) entry.getKey();
                Document value = (Document) entry.getValue();
                String[] keys = key.split("_");
                String materialNo = keys[0];
                String batchNo = keys[1];
                String stockNo = keys[2];
                double estPrice = VtuzxUtil.getDouble(value, "estPrice");
                double taxRate = VtuzxUtil.getDouble(value, "taxRate");
                double count = VtuzxUtil.getDouble(value, "count");
                String unitName = VtuzxUtil.getString(value, "unit");
                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber"
                ), cond);
                //获取单位编码
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }
                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");//产品类型
                colMap.put("FMaterialId", new Document("FNumber", materialNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", 1);//实发数量
                colMap.put("FTaxPrice", estPrice);//含税单价
                colMap.put("FIsFree", false);//是否赠品
                colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                colMap.put("FLot", new Document("FNumber", batchNo));//批号
                colMap.put("FEntryTaxRate", taxRate);//税率
                colMap.put("FStockId", new Document("FNumber", stockNo));//仓库
                colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSALUNITQTY", count);//销售数量
                colMap.put("FSALBASEQTY", count);//销售基本数量
                colMap.put("FPRICEBASEQTY", count);//计价基本数量
                colMap.put("FOUTCONTROL", false);//控制出库数量
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", count);//未关联应付数量（计价单位
                colMap.put("FCheckDelivery", false);//发货检验
                FEntity.add(colMap);

            }

        }


        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        //晓芹创建销售出库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_OUTSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(orderNo + e.getMessage());
//            throw new VtuzxException("晓芹" + e.getMessage());
        }
    }

    //晓芹销售出(公司间结算调拨类型)
    private void syncKingdeeSaleAlocOne(VtuzxKingdeeCloudClient client, Document data, Document historyDoc) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        //查询销售单获取客户信息
        Long gmtCreate = VtuzxUtil.getObject(data, "gmtCreate");//创建时间
        Date gmtDate = new Date(gmtCreate);
        Calendar right = Calendar.getInstance();
        right.setTime(gmtDate);
        right.add(Calendar.MONTH, -2);
        Date startDate = right.getTime();
        String startTime = VtuzxUtil.formatYmdHmsF(startDate);
        right.add(Calendar.MONTH, 5);
        Date endDate = right.getTime();
        String endTime = VtuzxUtil.formatYmdHmsF(endDate);


        String departMentId = "";//金蝶部门id
        String stockId = "";//仓库id

        String orderNo = VtuzxUtil.getString(data, "orderNo");
        String sourceBillNo = VtuzxUtil.getString(data, "sourceBillNo");

        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSCKD01_SYS"));//单据类型 标准销售出库单
        payModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date(gmtCreate)));//单据日期
//        payModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));//单据日期
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        payModel.put("FCustomerID", new Document("FNumber", "CUST0099"));//客户 固定野象
        payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织
        payModel.put("FDeliveryDeptID", new Document("FNumber", departMentId));//发货部门
        payModel.put("FReceiverID", new Document("FNumber", "CUST0099"));//收货方 固定野象
        payModel.put("FSettleID", new Document("FNumber", "CUST0099"));//结算方 固定野象
        payModel.put("FPayerID", new Document("FNumber", "CUST0099"));//付款方 固定野象
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务或费用
        payModel.put("F_XSCK_JKYDJH", orderNo);

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FIsIncludedTax", true);//是否含税
        SubHeadEntity.put("FLocalCurrID", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        SubHeadEntity.put("FIsPriceExcludeTax", true);//价外税
        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据

        //查询出库单获取出库信息(唯一码出库)
        if (!VtuzxUtil.isEmpty(sourceBillNo)) {
            List<String> serialNoList = new ArrayList<>();//存放唯一码集合
            List<Document> serialList = new ArrayList<>();//唯一码和单价等相关信息集合

            //查询极客云出库单
            VtuzxMap param = new VtuzxMap();
            param.append("pageSize", 1)
                    .append("selelctFields", "recId,goodsdocNo,inOutDate,gmtCreate,inouttypeName,vendCustomerName,warehouseCode,warehouseName,comment,companyId,companyName,inOutReason,goodsDocDetailList.recId,goodsDocDetailList.goodsNo,goodsDocDetailList.goodsName,goodsDocDetailList.goodsName,goodsDocDetailList.skuId,goodsDocDetailList.skuName,goodsDocDetailList.skuBarcode,goodsDocDetailList.unitName,goodsDocDetailList.quantity,goodsDocDetailList.serialNo,goodsDocDetailList.estPrice,goodsDocDetailList.taxRate")
                    .append("sourceBillNo", sourceBillNo)
                    .append("endDate", endTime)
                    .append("startDate", startTime)
                    .append("pageIndex", 0);
            VtuzxMap stotrageDoc = jiKeYunApiService.getStorageOut(storeDoc, param);
            Map<String, Object> outresult = VtuzxUtil.getObject(stotrageDoc, "result");
            List<Map<String, Object>> outdata = VtuzxUtil.getObject(outresult, "data");
            Map<String, Object> outDoc = outdata.get(0);
            List<Map<String, Object>> goodsDocDetailList = VtuzxUtil.getObject(outDoc, "goodsDocDetailList");//出库货品信息
            for (Map<String, Object> goodsMap : goodsDocDetailList) {
                String jackSerialNo = VtuzxUtil.getString(goodsMap, "serialNo");
                String goodsNo = VtuzxUtil.getString(goodsMap, "goodsNo");
                String unitName = VtuzxUtil.getString(goodsMap, "unitName");
                double estPrice = VtuzxUtil.getDouble(goodsMap, "estPrice");//含税单价
                double taxRate = VtuzxUtil.getDouble(goodsMap, "taxRate");//税率
                double quantity = VtuzxUtil.getDouble(goodsMap, "quantity");//出库数量

                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber"
                ), cond);
                //获取单位编码
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }
                String serialNo = "";
                if (!VtuzxUtil.isEmpty(jackSerialNo)) {//是唯一码出库
                    if (jackSerialNo.startsWith("HTTP://ZS")) {
                        StringBuilder sb = new StringBuilder(jackSerialNo.toLowerCase());
                        sb.setCharAt(49, 'Z');
                        sb.setCharAt(44, 'C');
                        serialNo = sb.toString();
                        serialNoList.add(serialNo);
                        Document document = new Document();
                        document.append("estPrice", estPrice)
                                .append("taxRate", taxRate)
                                .append("unit", unitName)
                                .append("serialNo", serialNo);
                        serialList.add(document);
                    }
                    //查询唯一码所在仓库
                } else {//不是唯一码出库
                    //判断是否启用批号(单位编码)
                    String floatCond = String.format("FNumber = '%s'", goodsNo);
                    List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                            "FIsBatchManage",
                            "FMATERIALID"
                    ), floatCond);

                    boolean flag = true;
                    String materialId = "";//物料编码id
                    if (bd_Material != null && bd_Material.size() > 0) {
                        flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                        materialId = bd_Material.get(0).getString("FMATERIALID");
                    }
                    //查询即时库存取物料仓库信息
                    String inventoryCond = String.format("FMaterialId = '%s' and FBaseQty > '%d'", materialId, 0);
                    List<VtuzxMap> bd_inventory = kingdeeService.query(client, "STK_Inventory", new VtuzxArrayList<>(
                            "FStockId",
                            "FMaterialId",
                            "FLot",
                            "FBaseQty"
                    ), inventoryCond);

                    List<VtuzxMap> colMapList = new ArrayList<>();
                    for (VtuzxMap inventoryMap : bd_inventory) {
                        double residue = VtuzxUtil.getDouble(inventoryMap, "FBaseQty");
                        if (residue >= quantity) {
                            inventoryMap.replace("FBaseQty", quantity);
                            colMapList.add(inventoryMap);
                            break;
                        } else {//如果数量不够扣的话
                            quantity -= residue;
                            colMapList.add(inventoryMap);
                        }
                    }
                    //循环添加但具体数据
                    for (VtuzxMap map : colMapList) {
                        String stockNoId = VtuzxUtil.getString(map, "FStockId");//仓库Id
                        String flotNoId = VtuzxUtil.getString(map, "FLot");//批号id
                        double count = VtuzxUtil.getDouble(map, "FBaseQty");
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");//产品类型
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", count);//实发数量
                        colMap.put("FTaxPrice", estPrice);//含税单价
                        colMap.put("FIsFree", false);//是否赠品
                        colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                        colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                        String batchNo = "";
                        if (flag) {
                            String batchCond = String.format("FLOTID  = '%s'", flotNoId);
                            List<VtuzxMap> bd_batch = kingdeeService.query(client, "BD_BatchMainFile", new VtuzxArrayList<>(
                                    "FNumber"
                            ), batchCond);
                            if (bd_batch != null && bd_batch.size() > 0) {
                                batchNo = bd_batch.get(0).getString("FNumber");
                            }
                            colMap.put("FLot", new Document("FNumber", batchNo));//批号
                        }
                        colMap.put("FEntryTaxRate", taxRate);//税率
                        //查询仓库
                        String stockCond = String.format("FStockId = '%s'", stockNoId);
                        List<VtuzxMap> bd_stock = kingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
                                "FNumber"
                        ), stockCond);
                        if (bd_stock != null && bd_stock.size() > 0) {
                            stockId = bd_stock.get(0).getString("FNumber");
                        }
                        colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                        colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSALUNITQTY", count);//销售数量
                        colMap.put("FSALBASEQTY", count);//销售基本数量
                        colMap.put("FPRICEBASEQTY", count);//计价基本数量
                        colMap.put("FOUTCONTROL", false);//控制出库数量
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", count);//未关联应付数量（计价单位
                        colMap.put("FCheckDelivery", false);//发货检验
                        FEntity.add(colMap);
                    }
                }
            }
            //去及时库存查询仓库和批次等信息，先查询内层表
            List<ObjectId> inventoryIdList = new ArrayList<>();
            List<Document> inventoryDetailList = new ArrayList<>();
            Iterator<Document> inventoryDetailItr = inventoryDetailDao.findList(Criteria.where("traceBack.traceBackNo").in(serialNoList), null, 0, 0);
            while (inventoryDetailItr.hasNext()) {
                Document detailDoc = inventoryDetailItr.next();
                ObjectId _inventoryId = VtuzxUtil.getObject(detailDoc, "_inventoryId");
                if (!inventoryIdList.contains(_inventoryId)) {
                    inventoryIdList.add(_inventoryId);
                }
                inventoryDetailList.add(detailDoc);
            }
            //去外层表查询批号信息
            List<Document> inventoryList = new ArrayList<>();
            Iterator<Document> inventoryItr = inventoryDao.findList(Criteria.where("_id").in(inventoryIdList), null, 0, 0);
            while (inventoryItr.hasNext()) {
                Document inventoryDoc = inventoryItr.next();
                inventoryList.add(inventoryDoc);
            }
            //把批号信息添加到内层
            for (Document document : inventoryDetailList) {
                ObjectId _inventoryId = VtuzxUtil.getObject(document, "_inventoryId");
                for (Document doc : inventoryList) {
                    ObjectId _id = VtuzxUtil.getObject(doc, "_id");
                    if (_inventoryId.equals(_id)) {
                        String batchNo = VtuzxUtil.getString(doc, "batchNo");
                        String materialNo = VtuzxUtil.getString(doc, "materialNo");
                        document.append("batchNo", batchNo)
                                .append("materialNo", materialNo);
                        break;
                    }
                }
            }

            Map<String, Document> dataMap = new HashMap<>();//k:物料 + 批次 + 仓库 v:唯一码相关信息(数量，单价，税率)
            //把数据整理到map集合里
            for (Document document : serialList) {
                String serialNo = VtuzxUtil.getString(document, "serialNo");
                for (Document doc : inventoryDetailList) {//及时库存
                    List<Document> traceBack = VtuzxUtil.getObject(doc, "traceBack");
                    for (Document serialDoc : traceBack) {
                        String traceBackNo = VtuzxUtil.getString(serialDoc, "traceBackNo");
                        if (serialNo.equals(traceBackNo)) {
                            String materialNo = VtuzxUtil.getString(doc, "materialNo");
                            String batchNo = VtuzxUtil.getString(doc, "batchNo");
                            String stockNo = VtuzxUtil.getString(doc, "stockNo");
                            Document serialData = dataMap.get(materialNo + "_" + batchNo + "_" + stockNo);
                            if (VtuzxUtil.isEmpty(serialData)) {//如果从map集合中获取的数据为空
                                Document serial = new Document();
                                serial.append("count", 1)
                                        .append("unit", VtuzxUtil.getString(document, "unit"))
                                        .append("estPrice", VtuzxUtil.getDouble(document, "estPrice"))//含税单价
                                        .append("taxRate", VtuzxUtil.getDouble(document, "taxRate"));//税率
                                dataMap.put(materialNo + "_" + batchNo + "_" + stockNo, serial);
                                break;
                            } else {//如果有数据的话,把数量改一下
                                double count = VtuzxUtil.getDouble(serialData, "count");
                                serialData.replace("count", count + 1);
                                dataMap.put(materialNo + "_" + batchNo + "_" + stockNo, serialData);
                                break;
                            }

                        }
                    }
                }
            }
            //循环map集合向金蝶添加数据
            for (Map.Entry entry : dataMap.entrySet()) {
                String key = (String) entry.getKey();
                Document value = (Document) entry.getValue();
                String[] keys = key.split("_");
                String materialNo = keys[0];
                String batchNo = keys[1];
                String stockNo = keys[2];
                double estPrice = VtuzxUtil.getDouble(value, "estPrice");
                double taxRate = VtuzxUtil.getDouble(value, "taxRate");
                double count = VtuzxUtil.getDouble(value, "count");
                String unitName = VtuzxUtil.getString(value, "unit");
                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber"
                ), cond);
                //获取单位编码
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }
                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");//产品类型
                colMap.put("FMaterialId", new Document("FNumber", materialNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", 1);//实发数量
                colMap.put("FTaxPrice", estPrice);//含税单价
                colMap.put("FIsFree", false);//是否赠品
                colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                colMap.put("FLot", new Document("FNumber", batchNo));//批号
                colMap.put("FEntryTaxRate", taxRate);//税率
                colMap.put("FStockId", new Document("FNumber", stockNo));//仓库
                colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSALUNITQTY", count);//销售数量
                colMap.put("FSALBASEQTY", count);//销售基本数量
                colMap.put("FPRICEBASEQTY", count);//计价基本数量
                colMap.put("FOUTCONTROL", false);//控制出库数量
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", count);//未关联应付数量（计价单位
                colMap.put("FCheckDelivery", false);//发货检验
                FEntity.add(colMap);
            }
        }


        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        //晓芹创建销售出库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_OUTSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(orderNo + e.getMessage());
//            throw new VtuzxException("晓芹" + e.getMessage());
        }
    }

    //野象销售出(公司间结算)
    private void suncKingdeeSaleOutOneYX(VtuzxKingdeeCloudClient client, Document data, Document historyDoc) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        Long gmtCreate = VtuzxUtil.getObject(data, "gmtCreate");//创建时间
        String outReldataName = VtuzxUtil.getString(data, "outReldataName");//供货方名称(仓库)
        String outReldataId = VtuzxUtil.getString(data, "outReldataId");//供货方id
        //根据供货方名称查询对应的店铺
        Document channelDoc = channelDao.findOne(Criteria.where("warehouseName").is(outReldataName).and("companyName").regex("野象"));
        //渠道查询不到的给与提示
        if (VtuzxUtil.isEmpty(channelDoc)) {
            throw new VtuzxException("没有查询到渠道信息,请维护渠道");
        }
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        String channelName = VtuzxUtil.getString(channelDoc, "channelName");//店铺名称
        String departMentId = "";//金蝶部门id
        String stockId = VtuzxUtil.getString(data, "stockId");//金蝶仓库id

        if (outReldataName.contains("外埠")) {
            departMentId = "05";
            stockId = "YXWB01";
        } else {//去仓库接口查询部门和仓库
            VtuzxMap stockMap = new VtuzxMap();
            stockMap.append("pageIndex", 0).append("name", outReldataName).append("pageSize", 2);
            VtuzxMap stock = jiKeYunApiService.getStock(storeDoc, stockMap);
            Map<String, Object> result = VtuzxUtil.getObject(stock, "result");
            Map<String, Object> stockData = VtuzxUtil.getObject(result, "data");
            List<Map<String, Object>> warehouseInfo = VtuzxUtil.getObject(stockData, "warehouseInfo");
            stockId = VtuzxUtil.getString(warehouseInfo.get(0), "warehouseCode");//获取仓库编号
            departMentId = VtuzxUtil.getString(warehouseInfo.get(0), "warehouseDepartCode");//获取部门编号
        }

        String orderNo = VtuzxUtil.getString(data, "orderNo");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSCKD01_SYS"));//单据类型 标准销售出库单
        payModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date(gmtCreate)));//单据日期
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        payModel.put("FCustomerID", new Document("FNumber", "CUST0005"));//客户 固定晓芹
        payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织
        payModel.put("FDeliveryDeptID", new Document("FNumber", departMentId));//发货部门
        payModel.put("FReceiverID", new Document("FNumber", "CUST0005"));//收货方 固定晓芹
        payModel.put("FSettleID", new Document("FNumber", "CUST0005"));//结算方 固定晓芹
        payModel.put("FPayerID", new Document("FNumber", "CUST0005"));//付款方 固定晓芹
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务或费用
        payModel.put("F_PSUH_JSDH", orderNo);//吉客云结算单号
        payModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        payModel.put("F_PSUH_DPMC", channelName);//店铺名称

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FIsIncludedTax", true);//是否含税
        SubHeadEntity.put("FLocalCurrID", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        SubHeadEntity.put("FIsPriceExcludeTax", true);//价外税
        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据

        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合
        Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
        List<String> materialNoList = new ArrayList<>();//物料编码集合为了查询税率
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
            if (!materialNoList.contains(goodsNo)) {
                materialNoList.add(goodsNo);
            }
            Document getGoods = (Document) goodsMap.get(goodsNo);
            if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                goodsMap.put(goodsNo, doc);
            } else {
                int skuCount = VtuzxUtil.getInt(doc, "skuCount");
                int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                doc.replace("skuCount", skuCount + skuNowCount);
                goodsMap.put(goodsNo, doc);
            }
        }

        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");

            priceMap.put(materialNo, currentPrice);
        }

        //循环货品集合，添加金蝶单据体信息
        for (Map.Entry entry : goodsMap.entrySet()) {
            Document entryDoc = (Document) entry.getValue();
            String goodsNo = VtuzxUtil.getString(entryDoc, "goodsNo");
            String unitName = VtuzxUtil.getString(entryDoc, "unitName");
//            double taxRate = VtuzxUtil.getDouble(entryDoc, "taxRate");//税率
//            double settPrice = VtuzxUtil.getDouble(entryDoc, "settPrice");//结算金额
            double settPrice = (double) priceMap.get(goodsNo);


            int skuCount = VtuzxUtil.getInt(entryDoc, "skuCount");
            //查询单位编码，直接传文字无效
            String unit = (String) unitMap.get(unitName);

            //添加单据体
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
            colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
            colMap.put("FRealQty", skuCount);//实发数量
            colMap.put("FTaxPrice", settPrice);//含税单价
            //金额为0就是赠品
            if (settPrice == 0) {
                colMap.put("FIsFree", true);//是否赠品
            } else {
                colMap.put("FIsFree", false);//是否赠品
            }

            colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
            colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
//                colMap.put("FLot", new Document("FNumber", batchNo));//批号
            double taxRate = (Double) taxMap.get(goodsNo);
            colMap.put("FEntryTaxRate", taxRate);//税率
            colMap.put("FStockId", new Document("FNumber", stockId));//仓库
            colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
            colMap.put("FSALUNITQTY", skuCount);//销售数量
            colMap.put("FSALBASEQTY", skuCount);//销售基本数量
            colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
            colMap.put("FOUTCONTROL", false);//控制出库数量
            colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
            colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
            colMap.put("FCheckDelivery", false);//发货检验
            FEntity.add(colMap);
        }
        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        //创建销售出库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_OUTSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(orderNo + e.getMessage());
        }
    }

    //野象采购退(公司间结算)
    private void syncKingdeeRefund(VtuzxKingdeeCloudClient client, Document data, Document historyDoc, String orderTime) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String orderNo = VtuzxUtil.getString(data, "orderNo");
//        Long settDate = VtuzxUtil.getObject(data, "settDate");//结算时间
//        String orderTime = VtuzxUtil.getString(data, "orderTime");//结算时间
        String outReldataName = VtuzxUtil.getString(data, "outReldataName");//收货方
        String stockId = VtuzxUtil.getString(data, "stockId");//金蝶仓库id

        Map<String, Object> model = new LinkedHashMap<>();//采购退料单总参
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID", new Document("FNUMBER", "TLD01_SYS"));//单据类型 标准退料单
        model.put("FBusinessType", "CG");//业务类型

        if (!VtuzxUtil.isEmpty(orderTime)) {
            model.put("FDate", orderTime);//发货日期
        } else {
            model.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));//单据日期
        }
        model.put("FMRTYPE", "B");//退料类型
        model.put("FMRMODE", "A");//退料方式
        model.put("FStockOrgId", new Document("FNumber", "200"));//退料组织
//        model.put("FMRDeptId", new Document("FNumber", departMentId));//退料部门
        model.put("FRequireOrgId", new Document("FNumber", "200"));//需求组织
        model.put("FPurchaseOrgId", new Document("FNumber", "200"));//采购组织
//        model.put("FPURCHASEDEPTID", new Document("FNumber", departMentId));//采购部门
        model.put("FSupplierID", new Document("FNumber", "05.0002"));//应收公司野象传金蝶野象采购退
//        model.put("FACCEPTORID", new Document("FNumber", "01.0001"));//接收方先固定晓芹
//        model.put("FSettleId", new Document("FNumber", "01.0001"));//结算方固定晓芹
//        model.put("FCHARGEID", new Document("FNumber", "01.0001"));//收款方先固定晓芹
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        model.put("FOwnerIdHead", new Document("FNumber", "200"));//货主
        model.put("F_PSUH_JSDH", orderNo);//吉客云结算单号

        Map<String, Object> purmrbfin = new LinkedHashMap<>();//财务信息参数
        purmrbfin.put("FSettleOrgId", new Document("FNumber", "200"));//结算组织
        purmrbfin.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        purmrbfin.put("FIsIncludedTax", true);//含税
        purmrbfin.put("FPRICETIMEPOINT", 1);//定价时点
        purmrbfin.put("FLOCALCURRID", new Document("FNumber", "PRE001"));//本位币
        purmrbfin.put("FEXCHANGETYPEID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        purmrbfin.put("FEXCHANGERATE", 1.0);//汇率
        purmrbfin.put("FISPRICEEXCLUDETAX", true);//价外税


        //根据结算单号查询货品信息
        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合

        List<String> materialNoList = new ArrayList<>();//物料编码集合为了查询税率
        for (Map<String, Object> goods : goodsList) {
            String goodsNo = VtuzxUtil.getString(goods, "goodsNo");
            if (!materialNoList.contains(goodsNo)) {
                materialNoList.add(goodsNo);
            }
        }
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");

            priceMap.put(materialNo, currentPrice);
        }

        //物料明细信息
        List<Map<String, Object>> purmrbEntry = new ArrayList<>();
        //循环货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
            String unitName = VtuzxUtil.getString(doc, "unitName");

//            double settPrice = VtuzxUtil.getDouble(doc, "settPrice");//结算金额
            double settPrice = (double) priceMap.get(goodsNo);
            Double skuCount = VtuzxUtil.getDouble(doc, "skuCount");
            skuCount = Math.abs(skuCount);

            //查询单位编码，直接传文字无效
            String unit = (String) unitMap.get(unitName);
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMATERIALID", new Document("FNumber", goodsNo));//物料编码
            //colMap.put("FMaterialDesc",);物料说明
            colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
            colMap.put("FRMREALQTY", skuCount);//实退数量
            colMap.put("FREPLENISHQTY", skuCount);//补料数量
            colMap.put("FKEAPAMTQTY", skuCount);//扣款数量
            colMap.put("FPRICEUNITID", new Document("FNumber", unit));//计价单位
            colMap.put("FSTOCKID", new Document("FNumber", "001"));//仓库
            colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            colMap.put("FIsReceiveUpdateStock", false);//收料更新库存状态
            //金蝶金额为0的就是赠品
            if (settPrice == 0) {
                colMap.put("FGiveAway", true);//是否赠品
            } else {
                colMap.put("FGiveAway", false);//是否赠品
            }

            colMap.put("FPriceBaseQty", skuCount);//基本计价数量
            colMap.put("FCarryUnitId", new Document("FNumber", unit));//采购单位
            colMap.put("FCarryQty", skuCount);//采购数量
            colMap.put("FCarryBaseQty", skuCount);//采购基本数量
            colMap.put("FBILLINGCLOSE", false);//立账关闭
//            colMap.put("FLot", new Document("FNumber", "88888"));//批号
            colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
            colMap.put("FOWNERID", new Document("FNumber", "200"));//货主
            //获取税率信息
            double taxRate = (Double) taxMap.get(goodsNo);
            colMap.put("FENTRYTAXRATE", taxRate);//税率
            colMap.put("FTAXPRICE", settPrice);//含税单价
            colMap.put("FIsStock", false);//是否扣库存
            purmrbEntry.add(colMap);
        }
        model.put("FPURMRBFIN", purmrbfin);
        model.put("FPURMRBENTRY", purmrbEntry);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "STK_InvCheckResult");
        payKneeParam.put("Model", model);

        //创建采购退料单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "PUR_MRB", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "PUR_MRB", "0", number);
            kingdeeService.audit(client, "PUR_MRB", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
//            _logger.info(e.getMessage());
            throw new VtuzxException(e.getMessage());
        }
    }

    //晓芹采购退(公司间结算)
    private void syncKingdeeRefundXY(VtuzxKingdeeCloudClient client, Document data, Document historyDoc) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String orderNo = VtuzxUtil.getString(data, "orderNo");
        Long settDate = VtuzxUtil.getObject(data, "settDate");//结算时间

        Map<String, Object> model = new LinkedHashMap<>();//采购退料单总参
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID", new Document("FNUMBER", "TLD01_SYS"));//单据类型 标准退料单
        model.put("FBusinessType", "CG");//业务类型
        model.put("FDate", VtuzxUtil.formatYmdHmsF(new Date(settDate)));//单据日期
        model.put("FMRTYPE", "B");//退料类型
        model.put("FMRMODE", "A");//退料方式
        model.put("FStockOrgId", new Document("FNumber", "100"));//退料组织
//        model.put("FMRDeptId", new Document("FNumber", departMentId));//退料部门
        model.put("FRequireOrgId", new Document("FNumber", "100"));//需求组织
        model.put("FPurchaseOrgId", new Document("FNumber", "100"));//采购组织
//        model.put("FPURCHASEDEPTID", new Document("FNumber", departMentId));//采购部门
        model.put("FSupplierID", new Document("FNumber", "VEN00047"));//应收公司
        model.put("FACCEPTORID", new Document("FNumber", "VEN00047"));//接收方先固定野象
        model.put("FSettleId", new Document("FNumber", "VEN00047"));//结算方固定野象
        model.put("FCHARGEID", new Document("FNumber", "VEN00047"));//收款方先固定野象
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        model.put("FOwnerIdHead", new Document("FNumber", "100"));//货主

        Map<String, Object> purmrbfin = new LinkedHashMap<>();//财务信息参数
        purmrbfin.put("FSettleOrgId", new Document("FNumber", "100"));//结算组织
        purmrbfin.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        purmrbfin.put("FIsIncludedTax", true);//含税
        purmrbfin.put("FPRICETIMEPOINT", 1);//定价时点
        purmrbfin.put("FLOCALCURRID", new Document("FNumber", "PRE001"));//本位币
        purmrbfin.put("FEXCHANGETYPEID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        purmrbfin.put("FEXCHANGERATE", 1.0);//汇率
        purmrbfin.put("FISPRICEEXCLUDETAX", true);//价外税


        //根据结算单号查询货品信息
        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合

        //物料明细信息
        List<Map<String, Object>> purmrbEntry = new ArrayList<>();
        //循环货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
            String unitName = VtuzxUtil.getString(doc, "unitName");
            double taxRate = VtuzxUtil.getDouble(doc, "taxRate");//税率
            double settPrice = VtuzxUtil.getDouble(doc, "settPrice");//结算金额
            int skuCount = VtuzxUtil.getInt(doc, "skuCount");
            skuCount = Math.abs(skuCount);

            //查询单位编码，直接传文字无效
            String cond = String.format("Fname = '%s'", unitName);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                    "FNumber",
                    "FNAME"
            ), cond);
            String unit = "";
            if (bd_customer != null && bd_customer.size() > 0) {
                unit = bd_customer.get(0).getString("FNumber");
            }

            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMATERIALID", new Document("FNumber", goodsNo));//物料编码
            //colMap.put("FMaterialDesc",);物料说明
            colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
            colMap.put("FRMREALQTY", skuCount);//实退数量
            colMap.put("FREPLENISHQTY", skuCount);//补料数量
            colMap.put("FKEAPAMTQTY", skuCount);//扣款数量
            colMap.put("FPRICEUNITID", new Document("FNumber", unit));//计价单位
            colMap.put("FSTOCKID", new Document("FNumber", "CK004"));//仓库固定退货仓库
            colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            colMap.put("FIsReceiveUpdateStock", false);//收料更新库存状态
            colMap.put("FGiveAway", false);//是否赠品
            colMap.put("FPriceBaseQty", skuCount);//基本计价数量
            colMap.put("FCarryUnitId", new Document("FNumber", unit));//采购单位
            colMap.put("FCarryQty", skuCount);//采购数量
            colMap.put("FCarryBaseQty", skuCount);//采购基本数量
            colMap.put("FBILLINGCLOSE", false);//立账关闭
            colMap.put("FLot", new Document("FNumber", "88888"));//批号
            colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
            colMap.put("FOWNERID", new Document("FNumber", "100"));//货主
            colMap.put("FENTRYTAXRATE", taxRate);//税率
            colMap.put("FTAXPRICE", settPrice);//含税单价
            colMap.put("FIsStock", false);//是否扣库存
            purmrbEntry.add(colMap);
        }
        model.put("FPURMRBFIN", purmrbfin);
        model.put("FPURMRBENTRY", purmrbEntry);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "STK_InvCheckResult");
        payKneeParam.put("Model", model);

        //创建采购退料单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "PUR_MRB", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "PUR_MRB", "0", number);
            kingdeeService.audit(client, "PUR_MRB", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(e.getMessage());
//            throw new VtuzxException(e.getMessage());
        }
    }

    //晓芹采购退(公司间结算)Task
    private void syncKingdeeRefundXYTask(VtuzxKingdeeCloudClient client, Document data, VtuzxMap materialMap, List<Document> dataList, Document historyDoc, VtuzxMap FID) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
//        String orderNo = VtuzxUtil.getString(data, "orderNo");
//        Long gmtCreate = VtuzxUtil.getObject(data, "gmtCreate");//结算时间
        Map<String, Object> model = new LinkedHashMap<>();//采购退料单总参
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID", new Document("FNUMBER", "TLD01_SYS"));//单据类型 标准退料单
        model.put("FBusinessType", "CG");//业务类型
        String gmtCreate = VtuzxUtil.getString(data, "gmtCreate");
        model.put("FDate", gmtCreate);//单据日期
        model.put("FMRTYPE", "B");//退料类型
        model.put("FMRMODE", "A");//退料方式
        String flagForFStockOrgId = VtuzxUtil.getString(FID, "flagForFStockOrgId");
        model.put("FStockOrgId", new VtuzxMap("FNumber", flagForFStockOrgId));//退料组织
        String flagForFRequireOrgId = VtuzxUtil.getString(FID, "flagForFRequireOrgId");
        model.put("FRequireOrgId", new VtuzxMap("FNumber", flagForFRequireOrgId));//需求组织
        String flagForFPurchaseOrgId = VtuzxUtil.getString(FID, "flagForFPurchaseOrgId");
        model.put("FPurchaseOrgId", new VtuzxMap("FNumber", flagForFPurchaseOrgId));//采购组织
        String flagForFSupplierID = VtuzxUtil.getString(FID, "flagForFSupplierID");
        model.put("FSupplierID", new VtuzxMap("FNumber", flagForFSupplierID));//应收公司
        String flagForFACCEPTORID = VtuzxUtil.getString(FID, "flagForFACCEPTORID");
        model.put("FACCEPTORID", new VtuzxMap("FNumber", flagForFACCEPTORID));//接收方
        String flagForFSettleId = VtuzxUtil.getString(FID, "flagForFSettleId");
        model.put("FSettleId", new VtuzxMap("FNumber", flagForFSettleId));//结算方
        String flagForFCHARGEID = VtuzxUtil.getString(FID, "flagForFCHARGEID");
        model.put("FCHARGEID", new VtuzxMap("FNumber", flagForFCHARGEID));//收款方
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        String flagForFOwnerIdHead = VtuzxUtil.getString(FID, "flagForFOwnerIdHead");
        model.put("FOwnerIdHead", new VtuzxMap("FNumber", flagForFOwnerIdHead));//货主
        Map<String, Object> purmrbfin = new LinkedHashMap<>();//财务信息参数
        String flagForFSettleOrgId = VtuzxUtil.getString(FID, "flagForFSettleOrgId");
        purmrbfin.put("FSettleOrgId", new VtuzxMap("FNumber", flagForFSettleOrgId));//结算组织
        purmrbfin.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        purmrbfin.put("FIsIncludedTax", true);//含税
        purmrbfin.put("FPRICETIMEPOINT", 1);//定价时点
        purmrbfin.put("FLOCALCURRID", new Document("FNumber", "PRE001"));//本位币
        purmrbfin.put("FEXCHANGETYPEID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        purmrbfin.put("FEXCHANGERATE", 1.0);//汇率
        purmrbfin.put("FISPRICEEXCLUDETAX", true);//价外税
        //根据单号查询货品信息
//        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
//        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
//        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
//        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合
        //物料明细信息
        List<Map<String, Object>> purmrbEntry = new ArrayList<>();
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息
        //循环货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : dataList) {
            Document fitDoc = new Document(goods);
            int isFit = VtuzxUtil.getInt(fitDoc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(fitDoc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> fitOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(fitOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.isEmpty(VtuzxUtil.getString(fitOrder, "goodsNo"))
                                ? VtuzxUtil.getString(fitOrder, "GoodsNo")
                                : VtuzxUtil.getString(fitOrder, "goodsNo");
                        String unitName = VtuzxUtil.isEmpty(VtuzxUtil.getString(fitOrder, "unitName"))
                                ? VtuzxUtil.getString(fitOrder, "Unit")
                                : VtuzxUtil.getString(fitOrder, "unitName");
                        double taxRate = VtuzxUtil.getDouble(fitOrder, "taxRate") == 0.0
                                ? VtuzxUtil.getDouble(fitOrder, "TaxRate")
                                : VtuzxUtil.getDouble(fitOrder, "taxRate");
                        int skuCount = VtuzxUtil.getInt(fitOrder, "skuCount") == 0
                                ? VtuzxUtil.getInt(fitOrder, "SellCount")
                                : VtuzxUtil.getInt(fitOrder, "skuCount");
                        Map<String, Object> priceMap = VtuzxUtil.getObject(FID, "priceMap");
                        double price = (double) priceMap.get(goodsNo);
                        VtuzxMap materialDoc = VtuzxUtil.getObject(materialMap, goodsNo);
                        String unit = VtuzxUtil.getString(materialDoc, "unit");
                        String unitId = "";
                        skuCount = Math.abs(skuCount);
                        //查询单位编码，直接传文字无效
                        String cond = String.format("Fname = '%s'", unitName);
                        List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                                "FNumber",
                                "FNAME"
                        ), cond);
                        if (bd_customer != null && bd_customer.size() > 0) {
                            unit = bd_customer.get(0).getString("FNumber");
                        }
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");//产品类型
                        colMap.put("FMATERIALID", new Document("FNumber", goodsNo));//物料编码
                        //colMap.put("FMaterialDesc",);物料说明
                        colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
                        colMap.put("FRMREALQTY", Math.abs(skuCount));//实退数量
                        colMap.put("FREPLENISHQTY", Math.abs(skuCount));//补料数量
                        colMap.put("FKEAPAMTQTY", Math.abs(skuCount));//扣款数量
                        colMap.put("FPRICEUNITID", new Document("FNumber", unit));//计价单位
                        String flagForFStockID = VtuzxUtil.getObject(FID, "flagForFStockID");
                        colMap.put("FStockID", new VtuzxMap("FNumber", flagForFStockID));//仓库
                        colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                        colMap.put("FIsReceiveUpdateStock", false);//收料更新库存状态
                        if (price == 0) {
                            colMap.put("FGiveAway", true);//是否赠品
                        } else {
                            colMap.put("FGiveAway", false);//是否赠品
                        }
                        colMap.put("FPriceBaseQty", Math.abs(skuCount));//基本计价数量
                        colMap.put("FCarryUnitId", new Document("FNumber", unit));//采购单位
                        colMap.put("FCarryQty", Math.abs(skuCount));//采购数量
                        colMap.put("FCarryBaseQty", Math.abs(skuCount));//采购基本数量
                        colMap.put("FBILLINGCLOSE", false);//立账关闭
                        //判断是否启用批号
                        String floatCond = String.format("FNumber = '%s'", goodsNo);
                        List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                "FIsBatchManage"
                        ), floatCond);
                        //获取单位编码
                        boolean flag = true;
                        if (bd_Material != null && bd_Material.size() > 0) {
                            flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                        }
                        if (flag) {
                            colMap.put("FLot", new Document("FNumber", "88888"));//批号
                        }
                        colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                        String flagForFOWNERID = VtuzxUtil.getObject(FID, "flagForFOWNERID");
                        colMap.put("FOWNERID", new VtuzxMap("FNumber", flagForFOWNERID));//货主
                        String flagForFOwnerID = VtuzxUtil.getObject(FID, "flagForFOwnerID");
                        colMap.put("FOwnerID", new VtuzxMap("FNumber", flagForFOwnerID));//货主
                        String flagForFOwnerId = VtuzxUtil.getObject(FID, "flagForFOwnerId");
                        colMap.put("FOwnerId", new VtuzxMap("FNumber", flagForFOwnerId));//货主
//                        colMap.put("FENTRYTAXRATE", taxRate);//税率
                        colMap.put("FIsStock", false);//是否扣库存
                        colMap.put("FTaxPrice", Math.abs(price));//含税单价
                        purmrbEntry.add(colMap);
                    }
                }
            } else {
                Document doc = new Document(goods);
                String goodsNo = VtuzxUtil.isEmpty(VtuzxUtil.getString(doc, "goodsNo"))
                        ? VtuzxUtil.getString(doc, "GoodsNo")
                        : VtuzxUtil.getString(doc, "goodsNo");
                String unitName = VtuzxUtil.isEmpty(VtuzxUtil.getString(doc, "unitName"))
                        ? VtuzxUtil.getString(doc, "Unit")
                        : VtuzxUtil.getString(doc, "unitName");
                double taxRate = VtuzxUtil.getDouble(doc, "taxRate") == 0.0
                        ? VtuzxUtil.getDouble(doc, "TaxRate")
                        : VtuzxUtil.getDouble(doc, "taxRate");
                int skuCount = VtuzxUtil.getInt(doc, "skuCount") == 0
                        ? VtuzxUtil.getInt(doc, "SellCount")
                        : VtuzxUtil.getInt(doc, "skuCount");
                Map<String, Object> priceMap = VtuzxUtil.getObject(FID, "priceMap");
                double price = (double) priceMap.get(goodsNo);
                VtuzxMap materialDoc = VtuzxUtil.getObject(materialMap, goodsNo);
                String unit = VtuzxUtil.getString(materialDoc, "unit");
                String unitId = "";
                skuCount = Math.abs(skuCount);
                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",
                        "FNAME"
                ), cond);
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }
                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");//产品类型
                colMap.put("FMATERIALID", new Document("FNumber", goodsNo));//物料编码
                //colMap.put("FMaterialDesc",);物料说明
                colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
                colMap.put("FRMREALQTY", Math.abs(skuCount));//实退数量
                colMap.put("FREPLENISHQTY", Math.abs(skuCount));//补料数量
                colMap.put("FKEAPAMTQTY", Math.abs(skuCount));//扣款数量
                colMap.put("FPRICEUNITID", new Document("FNumber", unit));//计价单位
                String flagForFStockID = VtuzxUtil.getObject(FID, "flagForFStockID");
                colMap.put("FStockID", new VtuzxMap("FNumber", flagForFStockID));//仓库
                colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                colMap.put("FIsReceiveUpdateStock", false);//收料更新库存状态
                if (price == 0) {
                    colMap.put("FGiveAway", true);//是否赠品
                } else {
                    colMap.put("FGiveAway", false);//是否赠品
                }
                colMap.put("FPriceBaseQty", Math.abs(skuCount));//基本计价数量
                colMap.put("FCarryUnitId", new Document("FNumber", unit));//采购单位
                colMap.put("FCarryQty", Math.abs(skuCount));//采购数量
                colMap.put("FCarryBaseQty", Math.abs(skuCount));//采购基本数量
                colMap.put("FBILLINGCLOSE", false);//立账关闭
                //判断是否启用批号
                String floatCond = String.format("FNumber = '%s'", goodsNo);
                List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FIsBatchManage"
                ), floatCond);
                //获取单位编码
                boolean flag = true;
                if (bd_Material != null && bd_Material.size() > 0) {
                    flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                }
                if (flag) {
                    colMap.put("FLot", new Document("FNumber", "88888"));//批号
                }
                colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                String flagForFOWNERID = VtuzxUtil.getObject(FID, "flagForFOWNERID");
                colMap.put("FOWNERID", new VtuzxMap("FNumber", flagForFOWNERID));//货主
                String flagForFOwnerID = VtuzxUtil.getObject(FID, "flagForFOwnerID");
                colMap.put("FOwnerID", new VtuzxMap("FNumber", flagForFOwnerID));//货主
                String flagForFOwnerId = VtuzxUtil.getObject(FID, "flagForFOwnerId");
                colMap.put("FOwnerId", new VtuzxMap("FNumber", flagForFOwnerId));//货主
//                colMap.put("FENTRYTAXRATE", taxRate);//税率
                colMap.put("FIsStock", false);//是否扣库存
                colMap.put("FTaxPrice", Math.abs(price));//含税单价
                purmrbEntry.add(colMap);
            }
        }
        String JKYDH = "";
        if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "allocateNo"))) {
            JKYDH = VtuzxUtil.getString(data, "tradeNo");
            model.put("F_PSUH_XSDH", JKYDH);
            model.put("F_PSUH_JSDH", JKYDH);
        } else if (VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "tradeNo"))) {
            JKYDH = VtuzxUtil.getString(data, "allocateNo");
            model.put("F_PSUH_JSDH", JKYDH);
        }
        model.put("FPURMRBFIN", purmrbfin);
        model.put("FPURMRBENTRY", purmrbEntry);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "STK_InvCheckResult");
        payKneeParam.put("Model", model);
        String number = "";
        historyDoc.append("param", new VtuzxMap("PUR_MRB", payKneeParam));
        //创建采购退料单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "PUR_MRB", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "PUR_MRB", "0", number);
            kingdeeService.audit(client, "PUR_MRB", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
            historyDoc.append("syncTask", true);
        } catch (Exception e) {
            if (e.getMessage().contains("更新库存不成功")) {//如果因为库存原因没有上传成功做一个其他入库后再审核
                VtuzxMap FIDOther = new VtuzxMap();
                String flagForFStockID = VtuzxUtil.getString(FID, "flagForFStockID");
                if (Objects.equals(flagForFStockOrgId, "200")) {
                    FIDOther.append("flagOtherForFSTOCKID", flagForFStockID)
                            .append("flagOtherForFStockOrgId", flagForFStockOrgId)
                            .append("flagOtherForFSUPPLIERID", "05.0002");
                } else if (Objects.equals(flagForFStockOrgId, "100")) {
                    FIDOther.append("flagOtherForFSTOCKID", flagForFStockID)
                            .append("flagOtherForFStockOrgId", flagForFStockOrgId)
                            .append("flagOtherForFSUPPLIERID", "05.0002");
                } else {
                    throw new VtuzxException(e.getMessage());
                }
                Exception recoveryException = null;
                try{
                    syncKingdeeOtherInBillTask(client, data, FIDOther);
                    kingdeeService.audit(client, "PUR_MRB", "0", number, "STK_InvCheckResult");
                    historyDoc.append("kingdeeNumber", number);
                    historyDoc.append("syncTask", true);
                } catch (Exception ex) {
                    recoveryException = ex;
                }
                //如果其他入库单异常
                if (recoveryException != null) {
                    VtuzxException finalException = new VtuzxException("库存更新失败，且创建其他入库单仍异常: " + recoveryException.getMessage());
                    finalException.initCause(e);
                    throw finalException;
                }
            } else {
                //如果不是更新库存不成功的异常,直接抛出
                throw new VtuzxException(e.getMessage());
            }
        }
    }

    //晓芹销售退(公司间结算)
    private void syncKingdeeSaleRefund(VtuzxKingdeeCloudClient client, Document data, Document historyDoc) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String orderNo = VtuzxUtil.getString(data, "orderNo");
        Long settDate = VtuzxUtil.getObject(data, "settDate");//结算时间
        Map<String, Object> saleModel = new LinkedHashMap<>();//销售退model
        saleModel.put("FID", 0);//实体主键
        saleModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型标准销售退货单
        saleModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date(settDate)));//单据日期
        saleModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        saleModel.put("FRetcustId", new Document("FNumber", "CUST0041"));//退货客户先固定野象
        saleModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        saleModel.put("FStockOrgId", new Document("FNumber", "100"));//库存组织
        saleModel.put("FReceiveCustId", new Document("FNumber", "CUST0041"));//收货方先固定野象
        saleModel.put("FSettleCustId", new Document("FNumber", "CUST0041"));//结算方先固定野象
        saleModel.put("FPayCustId", new Document("FNumber", "CUST0041"));//付款方先固定野象
        saleModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        saleModel.put("FIsTotalServiceOrCost", false);//整单服务标识
        saleModel.put("F_XSTH_JKYDJH", orderNo);//吉客云单据号

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        SubHeadEntity.put("FSettleOrgId", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        //根据结算单号查询货品信息
        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合
        List<Map<String, Object>> FEntity = new ArrayList<>();
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");//货品编号
            double taxRate = VtuzxUtil.getDouble(doc, "taxRate");//税率
            double settPrice = VtuzxUtil.getDouble(doc, "settPrice");//结算单价
            String unitName = VtuzxUtil.getString(doc, "unitName");
            int skuCount = VtuzxUtil.getInt(doc, "skuCount");
            skuCount = Math.abs(skuCount);
            //查询单位编码
            String cond = String.format("Fname = '%s'", unitName);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                    "FNumber",
                    "FNAME"
            ), cond);
            String unit = "";
            if (bd_customer != null && bd_customer.size() > 0) {
                unit = bd_customer.get(0).getString("FNumber");
            }
            //判断是否启用批号
            String floatCond = String.format("FNumber = '%s'", goodsNo);
            List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                    "FIsBatchManage"
            ), floatCond);
            //获取单位编码
            boolean flag = true;
            if (bd_Material != null && bd_Material.size() > 0) {
                flag = bd_Material.get(0).getBoolean("FIsBatchManage");
            }
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
            colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
            colMap.put("FRealQty", skuCount);//实退数量
            colMap.put("FTaxPrice", settPrice);//含税单价
            colMap.put("FIsFree", false);//是否赠品
            colMap.put("FEntryTaxRate", taxRate);//税率
            colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
            colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
            colMap.put("FOwnerId", new Document("FNumber", "100"));//货主
            colMap.put("FStockId", new Document("FNumber", "034"));//仓库固定售后退货仓
            colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            if (flag) {
                colMap.put("FLot", new Document("FNumber", "88888"));//批号
            }
            colMap.put("FDeliveryDate", VtuzxUtil.formatYmdHmsF(new Date(settDate)));//退货日期
            colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
            colMap.put("FSalUnitQty", skuCount);//销售数量
            colMap.put("FSalBaseQty", skuCount);//销售基本数量
            colMap.put("FPriceBaseQty", skuCount);//计价基本数量
            colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
            colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
            colMap.put("FIsReturnCheck", false);//退货校验
            FEntity.add(colMap);
        }
        saleModel.put("SubHeadEntity", SubHeadEntity);
        saleModel.put("FEntity", FEntity);

        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", false);
        kneeParam.put("IsEntryBatchFill", true);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", saleModel);

        //晓芹创建销售退货单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", kneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(orderNo + e.getMessage());
//            throw new VtuzxException(e.getMessage());
        }
    }

    //晓芹销售退(公司间结算)Task
    private void syncKingdeeSaleRefundTask(VtuzxKingdeeCloudClient client, Document data, Document historyDoc) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String orderNo = VtuzxUtil.getString(data, "orderNo");
        Long settDate = VtuzxUtil.getObject(data, "settDate");//结算时间
        Map<String, Object> saleModel = new LinkedHashMap<>();//销售退model
        saleModel.put("FID", 0);//实体主键
        saleModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型标准销售退货单
        saleModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date(settDate)));//单据日期
        saleModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        saleModel.put("FRetcustId", new Document("FNumber", "CUST0041"));//退货客户先固定野象
        saleModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        saleModel.put("FStockOrgId", new Document("FNumber", "100"));//库存组织
        saleModel.put("FReceiveCustId", new Document("FNumber", "CUST0041"));//收货方先固定野象
        saleModel.put("FSettleCustId", new Document("FNumber", "CUST0041"));//结算方先固定野象
        saleModel.put("FPayCustId", new Document("FNumber", "CUST0041"));//付款方先固定野象
        saleModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        saleModel.put("FIsTotalServiceOrCost", false);//整单服务标识
        saleModel.put("F_XSTH_JKYDJH", orderNo);//吉客云单据号

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        SubHeadEntity.put("FSettleOrgId", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        //根据结算单号查询货品信息
        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合
        List<Map<String, Object>> FEntity = new ArrayList<>();
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");//货品编号
            double taxRate = VtuzxUtil.getDouble(doc, "taxRate");//税率
            double settPrice = VtuzxUtil.getDouble(doc, "settPrice");//结算单价
            String unitName = VtuzxUtil.getString(doc, "unitName");
            int skuCount = VtuzxUtil.getInt(doc, "skuCount");
            skuCount = Math.abs(skuCount);
            //查询单位编码
            String cond = String.format("Fname = '%s'", unitName);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                    "FNumber",
                    "FNAME"
            ), cond);
            String unit = "";
            if (bd_customer != null && bd_customer.size() > 0) {
                unit = bd_customer.get(0).getString("FNumber");
            }
            //判断是否启用批号
            String floatCond = String.format("FNumber = '%s'", goodsNo);
            List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                    "FIsBatchManage"
            ), floatCond);
            //获取单位编码
            boolean flag = true;
            if (bd_Material != null && bd_Material.size() > 0) {
                flag = bd_Material.get(0).getBoolean("FIsBatchManage");
            }
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
            colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
            colMap.put("FRealQty", skuCount);//实退数量
            colMap.put("FTaxPrice", settPrice);//含税单价
            colMap.put("FIsFree", false);//是否赠品
//            colMap.put("FEntryTaxRate", taxRate);//税率
            colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
            colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
            colMap.put("FOwnerId", new Document("FNumber", "100"));//货主
            colMap.put("FStockId", new Document("FNumber", "034"));//仓库固定售后退货仓
            colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            if (flag) {
                colMap.put("FLot", new Document("FNumber", "88888"));//批号
            }
            colMap.put("FDeliveryDate", VtuzxUtil.formatYmdHmsF(new Date(settDate)));//退货日期
            colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
            colMap.put("FSalUnitQty", skuCount);//销售数量
            colMap.put("FSalBaseQty", skuCount);//销售基本数量
            colMap.put("FPriceBaseQty", skuCount);//计价基本数量
            colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
            colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
            colMap.put("FIsReturnCheck", false);//退货校验
            FEntity.add(colMap);
        }
        saleModel.put("SubHeadEntity", SubHeadEntity);
        saleModel.put("FEntity", FEntity);

        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", false);
        kneeParam.put("IsEntryBatchFill", true);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", saleModel);

        //晓芹创建销售退货单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", kneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(orderNo + e.getMessage());
//            throw new VtuzxException(e.getMessage());
        }
    }

    //野象销售退(公司间结算)
    private void syncKingdeeSaleRefundYX(VtuzxKingdeeCloudClient client, Document data, Document historyDoc) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String orderNo = VtuzxUtil.getString(data, "orderNo");
        String outReldataName = VtuzxUtil.getString(data, "outReldataName");//供货方
        //根据供货方名称查询对应的店铺
        Document channelDoc = channelDao.findOne(Criteria.where("warehouseName").is(outReldataName).and("companyName").regex("野象"));
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        String channelName = VtuzxUtil.getString(channelDoc, "channelName");//店铺名称
        Long settDate = VtuzxUtil.getObject(data, "settDate");//结算时间
        Map<String, Object> saleModel = new LinkedHashMap<>();//销售退model
        saleModel.put("FID", 0);//实体主键
        saleModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型标准销售退货单
        saleModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date(settDate)));//单据日期
        saleModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        saleModel.put("FRetcustId", new Document("FNumber", "CUST0005"));//退货客户先固定晓芹
        saleModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        saleModel.put("FStockOrgId", new Document("FNumber", "100"));//库存组织
        saleModel.put("FReceiveCustId", new Document("FNumber", "CUST0005"));//退货客户先固定晓芹
        saleModel.put("FSettleCustId", new Document("FNumber", "CUST0005"));//退货客户先固定晓芹
        saleModel.put("FPayCustId", new Document("FNumber", "CUST0005"));//退货客户先固定晓芹
        saleModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        saleModel.put("FIsTotalServiceOrCost", false);//整单服务标识
        saleModel.put("F_PSUH_JSDH", orderNo);//吉客云结算单号
        saleModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        saleModel.put("F_PSUH_DPMC", channelName);//店铺名称

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        SubHeadEntity.put("FSettleOrgId", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        //根据结算单号查询货品信息
        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合
        List<Map<String, Object>> FEntity = new ArrayList<>();

        List<String> materialNoList = new ArrayList<>();//物料编码集合为了查询税率
        for (Map<String, Object> goods : goodsList) {
            String goodsNo = VtuzxUtil.getString(goods, "goodsNo");//货品编号
            if (!materialNoList.contains(goodsNo)) {
                materialNoList.add(goodsNo);
            }
        }
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");

            priceMap.put(materialNo, currentPrice);
        }

        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");//货品编号
//            double taxRate = VtuzxUtil.getDouble(doc, "taxRate");//税率
//            double settPrice = VtuzxUtil.getDouble(doc, "settPrice");//结算单价
            String unitName = VtuzxUtil.getString(doc, "unitName");
            double settPrice = (double) priceMap.get(goodsNo);
            int skuCount = VtuzxUtil.getInt(doc, "skuCount");
            skuCount = Math.abs(skuCount);

            //查询单位编码
            String unit = (String) unitMap.get(unitName);
//            String cond = String.format("Fname = '%s'", unitName);
//            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
//                    "FNumber",
//                    "FNAME"
//            ), cond);
//            String unit = "";
//            if (bd_customer != null && bd_customer.size() > 0) {
//                unit = bd_customer.get(0).getString("FNumber");
//            }

            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
            colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
            colMap.put("FRealQty", skuCount);//实退数量
            colMap.put("FTaxPrice", settPrice);//含税单价
            //单价为0的话就是赠品
            if (settPrice == 0) {
                colMap.put("FIsFree", true);//是否赠品
            } else {
                colMap.put("FIsFree", false);//是否赠品
            }

            //获取税率
            double taxRate = (Double) taxMap.get(goodsNo);
            colMap.put("FEntryTaxRate", taxRate);//税率
            colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
            colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
            colMap.put("FOwnerId", new Document("FNumber", "100"));//货主
            colMap.put("FStockId", new Document("FNumber", "YXJDP01"));//仓库固定售后退货仓
            colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            colMap.put("FDeliveryDate", VtuzxUtil.formatYmdHmsF(new Date(settDate)));//退货日期
            colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
            colMap.put("FSalUnitQty", skuCount);//销售数量
            colMap.put("FSalBaseQty", skuCount);//销售基本数量
            colMap.put("FPriceBaseQty", skuCount);//计价基本数量
            colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
            colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
            colMap.put("FIsReturnCheck", false);//退货校验
            FEntity.add(colMap);
        }
        saleModel.put("SubHeadEntity", SubHeadEntity);
        saleModel.put("FEntity", FEntity);

        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", false);
        kneeParam.put("IsEntryBatchFill", true);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", saleModel);

        //创建销售退货单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", kneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
//            _logger.info(orderNo + e.getMessage());
            throw new VtuzxException(e.getMessage());
        }
    }


    //野象销售退(公司间结算)Task
    private void syncKingdeeSaleRefundYXTask(VtuzxKingdeeCloudClient client, Document data, Document historyDoc, VtuzxMap FID) throws Exception {
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String orderNo = VtuzxUtil.getString(data, "orderNo");
        String outReldataName = VtuzxUtil.getString(data, "outReldataName");//供货方
        //根据供货方名称查询对应的店铺
        Document channelDoc = channelDao.findOne(Criteria.where("warehouseName").is(outReldataName).and("companyName").regex("野象"));
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        String channelName = VtuzxUtil.getString(channelDoc, "channelName");//店铺名称
        Long settDate = VtuzxUtil.getObject(data, "settDate");//结算时间
        Map<String, Object> saleModel = new LinkedHashMap<>();//销售退model
        saleModel.put("FID", 0);//实体主键
        saleModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型标准销售退货单
        saleModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date(settDate)));//单据日期


        String flagForFSaleOrgId = VtuzxUtil.getObject(FID, "flagForFSaleOrgId");
        saleModel.put("FSaleOrgId", new VtuzxMap("FNumber", flagForFSaleOrgId));//销售组织
        ///saleModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织


        saleModel.put("FRetcustId", new Document("FNumber", "CUST0005"));//退货客户先固定晓芹
        saleModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        saleModel.put("FStockOrgId", new Document("FNumber", "100"));//库存组织
        saleModel.put("FReceiveCustId", new Document("FNumber", "CUST0005"));//退货客户先固定晓芹
        saleModel.put("FSettleCustId", new Document("FNumber", "CUST0005"));//退货客户先固定晓芹
        saleModel.put("FPayCustId", new Document("FNumber", "CUST0005"));//退货客户先固定晓芹
        saleModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        saleModel.put("FIsTotalServiceOrCost", false);//整单服务标识
        saleModel.put("F_PSUH_JSDH", orderNo);//吉客云结算单号
        saleModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        saleModel.put("F_PSUH_DPMC", channelName);//店铺名称

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        SubHeadEntity.put("FSettleOrgId", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        //根据结算单号查询货品信息
        VtuzxMap goodsParam = new VtuzxMap("orderNos", orderNo);
        VtuzxMap innerOrderGoods = jiKeYunApiService.getInnerOrderGoods(storeDoc, goodsParam);
        Map<String, Object> goodsResult = VtuzxUtil.getObject(innerOrderGoods, "result");
        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(goodsResult, "data");//调拨货品集合
        List<Map<String, Object>> FEntity = new ArrayList<>();

        List<String> materialNoList = new ArrayList<>();//物料编码集合为了查询税率
        for (Map<String, Object> goods : goodsList) {
            String goodsNo = VtuzxUtil.getString(goods, "goodsNo");//货品编号
            if (!materialNoList.contains(goodsNo)) {
                materialNoList.add(goodsNo);
            }
        }
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");

            priceMap.put(materialNo, currentPrice);
        }

        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");//货品编号
//            double taxRate = VtuzxUtil.getDouble(doc, "taxRate");//税率
//            double settPrice = VtuzxUtil.getDouble(doc, "settPrice");//结算单价
            String unitName = VtuzxUtil.getString(doc, "unitName");
            double settPrice = (double) priceMap.get(goodsNo);
            int skuCount = VtuzxUtil.getInt(doc, "skuCount");
            skuCount = Math.abs(skuCount);

            //查询单位编码
            String unit = (String) unitMap.get(unitName);
//            String cond = String.format("Fname = '%s'", unitName);
//            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
//                    "FNumber",
//                    "FNAME"
//            ), cond);
//            String unit = "";
//            if (bd_customer != null && bd_customer.size() > 0) {
//                unit = bd_customer.get(0).getString("FNumber");
//            }

            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FRowType", "Standard");//产品类型
            colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
            colMap.put("FUnitID", new Document("FNumber", unit));//库存单位
            colMap.put("FRealQty", skuCount);//实退数量
            colMap.put("FTaxPrice", settPrice);//含税单价
            //单价为0的话就是赠品
            if (settPrice == 0) {
                colMap.put("FIsFree", true);//是否赠品
            } else {
                colMap.put("FIsFree", false);//是否赠品
            }

            //获取税率
            double taxRate = (Double) taxMap.get(goodsNo);
//            colMap.put("FEntryTaxRate", taxRate);//税率
            colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
            colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
            colMap.put("FOwnerId", new Document("FNumber", "100"));//货主
            colMap.put("FStockId", new Document("FNumber", "YXJDP01"));//仓库固定售后退货仓
            colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            colMap.put("FDeliveryDate", VtuzxUtil.formatYmdHmsF(new Date(settDate)));//退货日期
            colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
            colMap.put("FSalUnitQty", skuCount);//销售数量
            colMap.put("FSalBaseQty", skuCount);//销售基本数量
            colMap.put("FPriceBaseQty", skuCount);//计价基本数量
            colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
            colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
            colMap.put("FIsReturnCheck", false);//退货校验
            FEntity.add(colMap);
        }
        saleModel.put("SubHeadEntity", SubHeadEntity);
        saleModel.put("FEntity", FEntity);

        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", false);
        kneeParam.put("IsEntryBatchFill", true);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", saleModel);

        //创建销售退货单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", kneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
//            _logger.info(orderNo + e.getMessage());
            throw new VtuzxException(e.getMessage());
        }
    }

    //极客云付款单传金蝶
    private void syncKingdeePayment(VtuzxKingdeeCloudClient client, Document data, Document historyDoc) throws Exception {
        Long billDate = VtuzxUtil.getObject(data, "billDate");//单据日期
        String oriBillNum = VtuzxUtil.getString(data, "oriBillNum");//销售结算单号
        String unitName = VtuzxUtil.getString(data, "unitName");//往来单位
        String billNum = VtuzxUtil.getString(data, "billNum");
        String unitTypeName = VtuzxUtil.getString(data, "unitTypeName");//往来单位类型(付款单位类型)
        String bankAccountName = VtuzxUtil.getString(data, "bankAccountName");//账户类型名称，对应金蝶结算方式(现金，银行)
        String tranName = VtuzxUtil.getString(data, "tranName");//收支项目用来判断金蝶单据的往来单位类型
        Integer payOutCuValue = VtuzxUtil.getInt(data, "payOutCuValue");
        String textLine = VtuzxUtil.getString(data, "textLine");//摘要(金蝶备注)
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        //通过销售结算单号查询销售单号
        String tradeNo = "";
        String shopName = "";//店铺名称
        if (!VtuzxUtil.isEmpty(oriBillNum)) {
            List<String> colsList = new ArrayList<>();//需要查询的字段
            colsList.add("tradeNo");
            colsList.add("tradeSettleOrder.mainTradeNo");
            colsList.add("tradeSettleOrder.shopName");
            VtuzxMap saleMap = jiKeYunApiService.getTradeSettleAllInfo(storeDoc,
                    new VtuzxMap()
                            .append("settleNo", oriBillNum)
                            .append("cols", colsList));
            Map<String, Object> saleResult = VtuzxUtil.getObject(saleMap, "result");
            List<Map<String, Object>> saleData = VtuzxUtil.getObject(saleResult, "data");
            if (!VtuzxUtil.isEmpty(saleData)) {
                Map<String, Object> trades = VtuzxUtil.getObject(saleData.get(0), "tradeSettleOrder");
                tradeNo = VtuzxUtil.getString(trades, "mainTradeNo");//销售单号
                shopName = VtuzxUtil.getString(trades, "shopName");//销售单号
            }
        }

        String FContactUnitType = "";//往来单位类型 同时查询对应类型的单位编码
        String FUnitNumber = "";//往来单位编码
        //供应商付款-供应商
        //客户付款-客户
        //员工借款，报销-员工
        if (tranName.contains("供应商")) {
            FContactUnitType = "BD_Supplier";
            String unitCond = String.format("Fname = '%s'", unitName);
            //查询供应商编码
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Supplier", new VtuzxArrayList<>(
                    "FNumber",//供应商编码
                    "FNAME"//供应商名称
            ), unitCond);
            if (bd_customer != null && bd_customer.size() > 0) {
                FUnitNumber = bd_customer.get(0).getString("FNumber");

            }
            if (VtuzxUtil.isEmpty(FUnitNumber)) {//如果供应商中的往来单位没有查到默认中台
                FUnitNumber = "03.0041";
            }

        } else if (tranName.contains("客户")) {
            FContactUnitType = "BD_Customer";
            String unitCond = String.format("Fname = '%s'", unitName);
            //查询客户编码
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                    "FNumber",//客户编码
                    "FNAME"//客户名称
            ), unitCond);
            if (bd_customer != null && bd_customer.size() > 0) {
                FUnitNumber = bd_customer.get(0).getString("FNumber");
            }
            if (VtuzxUtil.isEmpty(FUnitNumber)) {//如果客户中的往来单位没有查到默认野象
                FUnitNumber = "CUST0041";
            }
        } else if (tranName.contains("员工")) {
            FContactUnitType = "BD_Empinfo";
            String unitCond = String.format("Fname = '%s'", unitName);
            //查询员工编码
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Empinfo", new VtuzxArrayList<>(
                    "FNumber",//员工编码
                    "FNAME"//员工名称
            ), unitCond);
            if (bd_customer != null && bd_customer.size() > 0) {
                FUnitNumber = bd_customer.get(0).getString("FNumber");
            }
            if (VtuzxUtil.isEmpty(FUnitNumber)) {//如果员工中的往来单位没有查到默认野象
                FUnitNumber = "0036";
            }
        }

//        String setMethod = bankAccountName;//结算方式(金蝶结算方式编号对应吉客云结算方式名称)
        String setMethod = "";//结算方式
        if (bankAccountName.equals("银行")) {
            setMethod = "JSFS04_SYS";//银行
        } else {
            setMethod = "JSFS01_SYS";//现金
        }
        //如果付款单是客户退款，传金蝶收款退款单，其它的还是传金蝶付款单
        if (unitTypeName.equals("客户")) {
            String unitCode = VtuzxUtil.getString(data, "unitCode");//客户编码
            String customerId = "";//客户编码(金蝶)
            //先判断客户是否加密
            VtuzxMap customerMap = jiKeYunApiService.customerList(storeDoc,
                    new VtuzxMap("customerCode", unitCode));//客户编号

            Map<String, Object> customerResult = VtuzxUtil.getObject(customerMap, "result");
            List<Map<String, Object>> customerData = VtuzxUtil.getObject(customerResult, "data");
            //查询金蝶客户id,不存在的话做新增
            if (!VtuzxUtil.isEmpty(customerData)) {
                Map<String, Object> customerDoc = customerData.get(0);
                String nickName = VtuzxUtil.getString(customerDoc, "nickname");
                customerId = getCustomer(unitCode, client, data, nickName);
            } else {
                customerId = "01.00041";
            }
            String seller = VtuzxUtil.getString(data, "seller");//销售员
            String mainDepartName = "";
            String salesManId = "";
            if (!VtuzxUtil.isEmpty(seller)) {
                mainDepartName = getMainDepartName(seller, storeDoc);//吉客云部门名称
                salesManId = getSellId(seller, client);//金蝶业务员id
            }

            VtuzxMap Model = new VtuzxMap();//同步收款单api总参
            List<Map<String, Object>> FRefundBillEntry = new ArrayList<>();//付款单明细参数
            Model.append("FID", 0)
                    .append("FBillTypeID", new Document("FNUMBER", "SKTKDLX01_SYS"))//单据类型 销售业务退款单
                    .append("FDATE", VtuzxUtil.formatYmdHmsF(new Date(billDate)))//业务日期
                    .append("FCONTACTUNIT", new Document("FNumber", customerId))//往来单位，(客户)
                    .append("FRECTUNITTYPE", "BD_Customer")//收款单位类型,收款退款单全是客户
                    .append("FRECTUNIT", new Document("FNumber", customerId))//收款单位(客户)
                    .append("FCURRENCYID", new Document("FNumber", "PRE001"))//币别 固定人民币
                    .append("FPAYORGID", new Document("FNumber", "100"))//付款组织 先固定 开发销售测试
                    .append("FSETTLERATE", 1.0)//结算汇率
                    .append("FSETTLEORGID", new Document("FNumber", "100"))//结算组织 先固定 开发销售测试
                    .append("FSALEORGID", new Document("FNumber", "100"))//销售组织 先固定 开发销售测试
//                    .append("FSALEDEPTID", new Document("FNumber", deliveryDeptId))//销售部门 全部都是外埠
//                    .append("FSALEERID",new Document("FNumber",salesManId))//销售员
                    .append("FDOCUMENTSTATUS", "Z")//单据状态
                    .append("FBUSINESSTYPE", "1")//业务类型
                    .append("FISINIT", false)//是否初期单据
                    .append("FEXCHANGERATE", 1.0)//汇率
                    .append("FCancelStatus", "A")//作废状态
                    .append("FISSAMEORG", true)//是否相同组织
                    .append("FSETTLECUR", new Document("FNUMBER", "PRE001"))//结算币别
                    .append("FIsWriteOff", false)//是否转销
                    .append("FREMARK", textLine)//单据头备注，传极客云单据号
                    .append("FISB2C", false)
                    .append("FISCARRYRATE", false)//是否下推携带汇率到结算汇率
                    .append("FSETTLEMAINBOOKID", new Document("FNUMBER", "PRE001"))//结算本位币
                    .append("FMoreReceive", false)//多收款人
                    .append("F_ora_JKYDH", billNum)//吉客云单号
                    .append("F_PSUH_XSDH", tradeNo);//吉客云销售单号
            Map<String, Object> colMap = new HashMap<>();
            colMap.put("FSETTLETYPEID", new Document("FNumber", setMethod));//结算方式只有银行和现金两种
            if (setMethod.equals("JSFS04_SYS")) {//如果结算方式是银行需要添加银行账号
                colMap.put("FACCOUNTID", new Document("FNumber", "294783493586"));
            }
            colMap.put("FPURPOSEID", new Document("FNumber", "SFKYT02_SYS"));//付款用途 全部是预收款
            colMap.put("FREFUNDAMOUNTFOR", payOutCuValue);//表体应退金额
            colMap.put("FREFUNDAMOUNTFOR_E", payOutCuValue);//退款金额
            colMap.put("FNOTE", textLine);//备注，存极客云单据号
            colMap.put("FREFUNDAMOUNT_E ", payOutCuValue);//退款金额本位币
            colMap.put("FPOSTDATE", VtuzxUtil.formatYmdHmsF(new Date(billDate)));//登账日期
            colMap.put("FRuZhangType", "1");//入账类型必填项
            colMap.put("FPayType", "A");//支付类型(必填项)
            FRefundBillEntry.add(colMap);
            Model.append("FREFUNDBILLENTRY", FRefundBillEntry);

            Map<String, Object> kneeParam = new LinkedHashMap<>();
            kneeParam.put("NeedUpDateFields", new ArrayList<>());
            kneeParam.put("NeedReturnFields", new ArrayList<>());
            kneeParam.put("IsDeleteEntry", true);
            kneeParam.put("SubSystemId", "");
            kneeParam.put("IsVerifyBaseDataField", true);
            kneeParam.put("IsEntryBatchFill", false);
            kneeParam.put("ValidateFlag", true);
            kneeParam.put("NumberSearch", true);
            kneeParam.put("InterationFlags", "");
            kneeParam.put("Model", Model);
            historyDoc.append("param", kneeParam);
            //收款退款单
            try {
                List<VtuzxMap> customerList = kingdeeService.save(client, "AR_REFUNDBILL", kneeParam);
                VtuzxMap kingdeeCustomerMap = customerList.get(0);
                String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
                kingdeeService.submit(client, "AR_REFUNDBILL", "0", number);
                kingdeeService.audit(client, "AR_REFUNDBILL", "0", number, "STK_InvCheckResult");
                historyDoc.append("kingdeeNumber", number);
            } catch (Exception e) {
//                _logger.info( e.getMessage());
                throw new VtuzxException(e.getMessage());
            }
        } else {//如果不是客户退款传金蝶付款单
            Map<String, Object> Model = new HashMap<>();//同步付款单api总参
            List<Map<String, Object>> FpayBillEntry = new ArrayList<>();//付款单明细参数
            Model.put("FID", 0);
            Model.put("FBillTypeID", new Document("FNUMBER", "FKDLX01_SYS"));//单据类型 采购业务付款单
            Model.put("FDATE", VtuzxUtil.formatYmdHmsF(new Date(billDate)));//业务日期
            Model.put("FCONTACTUNIT", new Document("FNumber", "03.0041"));//往来单位默认中台
            Model.put("FCONTACTUNITTYPE", "BD_Supplier");//往来单位类型全是供应商
            Model.put("FRECTUNITTYPE", FContactUnitType);//收款单位类型供应商付款-供应商 客户付款-客户 员工借款，报销-员工
            Model.put("FRECTUNIT", new Document("FNumber", FUnitNumber));//收款单位 对应类型编码
            Model.put("FCURRENCYID", new Document("FNumber", "PRE001"));//币别 固定人民币
            Model.put("FPAYORGID", new Document("FNumber", "100"));//付款组织 先固定 开发销售测试
            Model.put("FSETTLERATE", 1.0);//结算汇率
            Model.put("FSETTLEORGID", new Document("FNumber", "100"));//结算组织 先固定 开发销售测试
            Model.put("FPURCHASEORGID", new Document("FNumber", "100"));//采购组织 先固定 开发销售测试
            Model.put("FPURCHASEDEPTID", new Document("FNumber", "01.01"));//采购部门 全部都是外埠
            Model.put("FDOCUMENTSTATUS", "Z");//单据状态
            Model.put("FBUSINESSTYPE", "2");//业务类型
            Model.put("FISINIT", false);//是否初期单据
            Model.put("FEXCHANGERATE", 1.0);//汇率
            Model.put("FCancelStatus", "A");//作废状态
            Model.put("FISSAMEORG", true);//是否相同组织
            Model.put("FIsCredit", false);//是否信贷业务
            Model.put("FSETTLECUR", new Document("FNUMBER", "PRE001"));//结算币别
            Model.put("FIsWriteOff", false);//是否转销
            Model.put("FREMARK", textLine);
            Model.put("FISB2C", false);
            Model.put("FIsWriteOff", false);//是否转销
            Model.put("FISCARRYRATE", false);
            Model.put("FISCARRYRATE", false);//是否下推携带汇率到结算汇率
            Model.put("FSETTLEMAINBOOKID", new Document("FNUMBER", "PRE001"));//结算本位币
            Model.put("FMoreReceive", false);//多收款人
            Model.put("F_ora_JKYDH", billNum);//吉客云单号
            Model.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
            Map<String, Object> colMap = new HashMap<>();
            colMap.put("FSETTLETYPEID", new Document("FNumber", setMethod));//结算方式只有银行和现金两种
            if (setMethod.equals("JSFS04_SYS")) {//如果结算方式是银行需要添加银行账号
                colMap.put("FACCOUNTID", new Document("FNumber", "8759522362252222"));
            }
            colMap.put("FPURPOSEID", new Document("FNumber", "SFKYT09_SYS"));//付款用途 全部是预收款
//                colMap.put("FPAYTOTALAMOUNTFOR_H",payOutCuValue);//表体应付金额
            colMap.put("FPAYTOTALAMOUNTFOR", payOutCuValue);//表体应付金额
            colMap.put("FPAYAMOUNTFOR_E", payOutCuValue);//付款金额
            colMap.put("FSETTLEPAYAMOUNTFOR", payOutCuValue);//折后金额
            colMap.put("FREALPAYAMOUNTFOR_D", payOutCuValue);//表体实付金额
            colMap.put("FPAYAMOUNT_E", payOutCuValue);//付款金额总位币
            colMap.put("FPOSTDATE", VtuzxUtil.formatYmdHmsF(new Date(billDate)));//登账日期
            colMap.put("FRuZhangType", "1");//入账类型必填项
            colMap.put("FPayType", "A");//支付类型(必填项)
            FpayBillEntry.add(colMap);
            Model.put("FPAYBILLENTRY", FpayBillEntry);
            Map<String, Object> kneeParam = new LinkedHashMap<>();
            kneeParam.put("NeedUpDateFields", new ArrayList<>());
            kneeParam.put("NeedReturnFields", new ArrayList<>());
            kneeParam.put("IsDeleteEntry", true);
            kneeParam.put("SubSystemId", "");
            kneeParam.put("IsVerifyBaseDataField", true);
            kneeParam.put("IsEntryBatchFill", false);
            kneeParam.put("ValidateFlag", true);
            kneeParam.put("NumberSearch", true);
            kneeParam.put("InterationFlags", "");
            kneeParam.put("Model", Model);
            historyDoc.append("param", kneeParam);
            //传金蝶付款单
            try {
                List<VtuzxMap> customerList = kingdeeService.save(client, "AP_PAYBILL", kneeParam);
                VtuzxMap kingdeeCustomerMap = customerList.get(0);
                String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
                kingdeeService.submit(client, "AP_PAYBILL", "0", number);
                kingdeeService.audit(client, "AP_PAYBILL", "0", number, "STK_InvCheckResult");
                historyDoc.append(billNum + "kingdeeNumber", number);
            } catch (Exception e) {
//                _logger.info(e.getMessage());
                throw new VtuzxException(e.getMessage());
            }
        }
    }

    //野象收款单
    private void syncKingdeeCollection(VtuzxKingdeeCloudClient client, Document data, Document historyDoc) throws Exception {
        Long billDate = VtuzxUtil.getObject(data, "billDate");//单据日期
        String unitCode = VtuzxUtil.getString(data, "unitCode");//客户编码
        String bankAccountName = VtuzxUtil.getString(data, "bankAccountName");//账户类型名称，对应金蝶结算方式(现金，银行)
        String tranName = VtuzxUtil.getString(data, "tranName");//收支往来项目
        String billNum = VtuzxUtil.getString(data, "billNum");
        String textLine = VtuzxUtil.getString(data, "textLine");//摘要(金蝶备注)
//        String oriBillNum = VtuzxUtil.getString(data,"oriBillNum");//销售结算单号
        String onlineShopTradeNo = VtuzxUtil.getString(data, "onlineShopTradeNo");//网店订单号
        //极客云token
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));

        String customerId = "";//客户编码(金蝶)
        //先判断客户是否加密
        VtuzxMap customerMap = jiKeYunApiService.customerList(storeDoc,
                new VtuzxMap("customerCode", unitCode));//客户编号

        Map<String, Object> customerResult = VtuzxUtil.getObject(customerMap, "result");
        List<Map<String, Object>> customerData = VtuzxUtil.getObject(customerResult, "data");
        Map<String, Object> customerDoc = null;
        if (!VtuzxUtil.isEmpty(customerData)) {
            customerDoc = customerData.get(0);
        } else {
            customerId = "CUST0012";//加密的客户固定
        }

        if (!VtuzxUtil.isEmpty(customerDoc)) {
            String nickName = VtuzxUtil.getString(customerDoc, "nickname");
            customerId = getCustomer(unitCode, client, data, nickName);
        }
        String seller = VtuzxUtil.getString(data, "seller");//销售员
        String mainDepartName = "";
        String salesManId = "";
        if (!VtuzxUtil.isEmpty(seller)) {
            mainDepartName = getMainDepartName(seller, storeDoc);//吉客云部门名称
            salesManId = getSellId(seller, client);//金蝶业务员id
        }

        String useTo = "";//收款用途
        //客户应收对应金蝶销售收款，客户预收对应金蝶预收款，
        if ("客户应收".equals(tranName)) {
            useTo = "SFKYT01_SYS";
        } else if ("客户预收".equals(tranName)) {
            useTo = "SFKYT02_SYS";
        }
//        String setMethod = bankAccountName;//结算方式(金蝶结算方式编号对应吉客云结算方式名称)
        String setMethod = "";//结算方式
        if (bankAccountName.equals("银行")) {
            setMethod = "JSFS04_SYS";//银行
        } else {
            setMethod = "JSFS01_SYS";//现金
        }

        List<Map<String, Object>> BillTransDetailList = VtuzxUtil.getObject(data, "billTransDetailList");//收支明细
        Map<String, Object> billMap = BillTransDetailList.get(0);
        Double cuValue = (Double.parseDouble(billMap.get("cuValue").toString()));


        //同步到金蝶
        Map<String, Object> Model = new HashMap<>();//同步收款单api总参
        List<Map<String, Object>> FReceiveBillEntry = new ArrayList<>();//收款单明细
        Model.put("FID", 0);
        Model.put("FBillTypeID", new Document("FNUMBER", "SKDLX01_SYS"));//单据类型
        Model.put("FDATE", VtuzxUtil.formatYmdHmsF(new Date(billDate)));//业务日期
        Model.put("FDATE", VtuzxUtil.formatYmdHmsF(new Date()));//业务日期
        Model.put("FCONTACTUNIT", new Document("FNumber", customerId));//往来单位，
        Model.put("FPAYUNITTYPE", "BD_Customer");//付款单位类型，固定都是客户
        Model.put("FPAYUNIT", new Document("FNumber", customerId));//付款单位 客户编码
        Model.put("FCURRENCYID", new Document("FNumber", "PRE001"));//币别 固定人民币
        Model.put("FPAYORGID", new Document("FNumber", "100"));//收款组织 先固定 开发销售测试
        Model.put("FSETTLERATE", 1.0);//结算汇率
        Model.put("FSETTLEORGID", new Document("FNumber", "100"));//结算组织 先固定 开发销售测试
        Model.put("FSALEORGID", new Document("FNumber", "100"));//销售组织 先固定 开发销售测试
        Model.put("FSALEDEPTID", new Document("FNumber", "06.02"));//销售部门
        Model.put("FSALEERID", new Document("FNumber", salesManId));//销售员
        Model.put("FDOCUMENTSTATUS", "Z");//单据状态
        Model.put("FBUSINESSTYPE", "1");//业务类型
        Model.put("FISINIT", false);//是否初期单据
        Model.put("FEXCHANGERATE", 1.0);//汇率
        Model.put("FCancelStatus", "A");//作废状态
        Model.put("FSETTLECUR", new Document("FNUMBER", "PRE001"));//结算币别
        Model.put("FISB2C", false);//BToC业务
        Model.put("FIsWriteOff", false);//是否转销
        Model.put("FREMARK", "外埠经销商预收货款");//备注
        Model.put("F_PSUH_BZZY", textLine);//备注(摘要)
        Model.put("FSETTLEMAINBOOKID", new Document("FNUMBER", "PRE001"));//结算本位币
        Model.put("FISCARRYRATE", false);//是否下推携带汇率到结算汇率
        Model.put("F_SKD_JKYDJH", billNum);//吉客云单据号
        Model.put("F_PSUH_XSDH", onlineShopTradeNo);//吉客云网店订单号

        Map<String, Object> colMap = new HashMap<>();
        colMap.put("FSETTLETYPEID", new Document("FNumber", setMethod));//结算方式只有银行和现金两种
        //TODO 银行先固定传
        if (setMethod.equals("JSFS04_SYS")) {//如果结算方式是银行需要添加银行账号
            colMap.put("FACCOUNTID", new Document("FNumber", "411910012810606"));
        }
        colMap.put("FPURPOSEID", new Document("FNumber", useTo));//收款用途
        colMap.put("FRECTOTALAMOUNTFOR", cuValue);//应收金额
        colMap.put("FRECAMOUNTFOR_E", cuValue);//收款金额
        colMap.put("FRECAMOUNT_E", cuValue);//收款金额总位币
        colMap.put("FPOSTDATE", VtuzxUtil.formatYmdHmsF(new Date(billDate)));//登账日期
        FReceiveBillEntry.add(colMap);
        Model.put("FRECEIVEBILLENTRY", FReceiveBillEntry);

        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", true);
        kneeParam.put("IsEntryBatchFill", false);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", Model);
        historyDoc.append("param", kneeParam);
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "AR_RECEIVEBILL", kneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "AR_RECEIVEBILL", "0", number);
            kingdeeService.audit(client, "AR_RECEIVEBILL", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            //_logger.info(billNum + e.getMessage());
            throw new VtuzxException(e.getMessage());
        }
    }

    //晓芹销售出(销售单)
    private void syncKingdeeSaleOutXQ(VtuzxKingdeeCloudClient client, VtuzxMap data, Document historyDoc) throws Exception {
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerId = "";//传金蝶的客户编号
        //先判断客户是否加密
        VtuzxMap customerMap = jiKeYunApiService.customerList(storeDoc,
                new VtuzxMap("customerCode", customerCode));//客户编号

        Map<String, Object> customerResult = VtuzxUtil.getObject(customerMap, "result");
        List<Map<String, Object>> customerData = VtuzxUtil.getObject(customerResult, "data");
        Map<String, Object> customerDoc = customerData.get(0);

        String nickName = VtuzxUtil.getString(customerDoc, "nickname");
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(nickName);
        if ((!m.find() && nickName.length() > 8) || VtuzxUtil.isEmpty(nickName)) {//说明是加密的
            customerId = "CUST0043";//加密的客户固定
        } else {//没加密先去金蝶查询是否存在，不存在做新增
            //查询客户
            String cond = String.format("FNumber = '%s'", customerCode);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                    "FNumber",//客户编码
                    "FNAME"//客户名称
            ), cond);
            if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                customerId = customerCode;
            } else {//没有的话做新增
                String telephone = VtuzxUtil.getString(customerMap, "phone");
                Map<String, Object> model = new LinkedHashMap<>();
                model.put("FCUSTID", 0);
                model.put("FCreateOrgId", new Document("FNumber", "100"));
                model.put("FNumber", customerCode);//客户编码
                model.put("FUseOrgId", new Document("FNumber", "100"));//使用组织
                model.put("FName", nickName);//客户姓名
                model.put("FCOUNTRY", new Document("FNumber", "China"));
                model.put("FTEL", telephone);
                model.put("FINVOICETITLE", nickName);//发票抬头
                model.put("FIsGroup", false);//集团客户
                model.put("FIsDefPayer", false);//默认付款方
                model.put("FCustTypeId", new Document("FNumber", "KHLB001_SYS"));//客户类别
                //TODO
                model.put("FGroup", new Document("FNumber", "01"));//客户分组
                model.put("FTRADINGCURRID", new Document("FNumber", "PRE001"));//结算币别
                model.put("FInvoiceType", "1");//发票类型
                model.put("FTaxType", new Document("FNumber", "SFL02_SYS"));//税分类
                model.put("FPriority", "1");//客户优先级
                model.put("FTaxRate", new Document("FNumber", "SL02_SYS"));//默认税率
                model.put("FISCREDITCHECK", true);//启用信用管理
                model.put("FIsTrade", true);//是否交易客户
                model.put("FUncheckExpectQty", false);//不校验可发量
                Map<String, Object> customerext = new LinkedHashMap<>();//商务信息
                customerext.put("FEnableSL", false);//启用商联在线
                customerext.put("FALLOWJOINZHJ", false);//允许对接智慧订货
                model.put("FT_BD_CUSTOMEREXT", customerext);
                Map<String, Object> kneeParam = new LinkedHashMap<>();
                kneeParam.put("NeedUpDateFields", new ArrayList<>());
                kneeParam.put("NeedReturnFields", new ArrayList<>());
                kneeParam.put("IsDeleteEntry", true);
                kneeParam.put("SubSystemId", "");
                kneeParam.put("IsVerifyBaseDataField", true);
                kneeParam.put("IsEntryBatchFill", false);
                kneeParam.put("ValidateFlag", true);
                kneeParam.put("NumberSearch", true);
                kneeParam.put("IsAutoAdjustField", false);
                kneeParam.put("InterationFlags", "");
                kneeParam.put("IgnoreInterationFlag", "");
                kneeParam.put("IsControlPrecision", false);
                kneeParam.put("ValidateRepeatJson", false);
                kneeParam.put("Model", model);
                try {
                    List<VtuzxMap> customerList = kingdeeService.save(client, "BD_Customer", kneeParam);
                    VtuzxMap kingdeeCustomerMap = customerList.get(0);
                    String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
                    kingdeeService.submit(client, "BD_Customer", "0", number);
                    kingdeeService.audit(client, "BD_Customer", "0", number, "STK_InvCheckResult");
                    customerId = customerCode;
                } catch (Exception e) {
                    _logger.info(e.getMessage());
                }
            }
        }

        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号
        VtuzxMap saleMap = jiKeYunApiService.getSaleBill(storeDoc,
                new VtuzxMap()
                        .append("tradeNo", tradeNo)
                        .append("pageSize", 50)
                        .append("pageIndex", 0)
                        .append("fields", "couponFee,gmtCreate,seller,onlineTradeNo,appendMemo,buyerMemo,sellerMemo,otherFee,discountFee,isFit,isGift,goodsMemo,tradeFrom,consignTime,goodsSerial.subTradeId,goodsSerial.skuId,goodsSerial.serialNo,warehouseName,warehouseCode,customerCode,goodsDetail.goodsNo,goodsDelivery.productionDate,goodsDelivery.expirationDate,goodsDelivery.batchNo,tradeNo,tradeStatus,warehouseCode,shopName,flagIds,sysFlagIds,flagNames,tradeCount,shareFavourableFee,warehouseCode,goodsDetail.unit,goodsDetail.goodsNo,goodsDetail.goodsName,goodsDetail.specName,goodsDetail.sellCount,goodsDetail.sellPrice,goodsDetail.taxRate,sellerMemo,goodsDelivery.batchNo,goodsSerial.serialNo"));

        Map<String, Object> tradeResult = VtuzxUtil.getObject(saleMap, "result");

        String tradeString = VtuzxUtil.getString(tradeResult, "data");
        Map<String, Object> tradeData = JSON.parseObject(tradeString, new TypeReference<HashMap<String, Object>>() {
        });
        JSONArray jsonArray = VtuzxUtil.getObject(tradeData, "Trades");
        JSONObject jsonTrades = (JSONObject) jsonArray.get(0);
        Map<String, Object> tradeMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : jsonTrades.entrySet()) {
            tradeMap.put(entry.getKey(), entry.getValue());
        }

        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(tradeMap, "TradeOrderAssemblyGoodsDtoList");//组合装信息
        List<Map<String, Object>> goodsSerials = VtuzxUtil.getObject(tradeMap, "GoodsSerials");//唯一码集合
        double otherFee = VtuzxUtil.getDouble(tradeMap, "OtherFee");//销售费用
        double discountFee = VtuzxUtil.getDouble(tradeMap, "DiscountFee");//整单优惠
        double couponFee = VtuzxUtil.getDouble(tradeMap, "CouponFee");//平台补贴(平台优惠)
        String sellerMemo = VtuzxUtil.getString(tradeMap, "SellerMemo");//备注(客服备注)
        String buyerMemo = VtuzxUtil.getString(tradeMap, "BuyerMemo");//(买家备注)客户备注
        String appendMemo = VtuzxUtil.getString(tradeMap, "AppendMemo");//追加备注
        String onlineTradeNo = VtuzxUtil.getString(tradeMap, "OnlineTradeNo");//网店订单号
        String seller = VtuzxUtil.getString(tradeMap, "Seller");//业务员
        String flagNames = VtuzxUtil.getString(tradeMap, "FlagNames");//标记名称
        String createTime = VtuzxUtil.getString(tradeMap, "GmtCreate");//创建日期
        Date createDate = VtuzxUtil.parseDate(createTime);
        Calendar right = Calendar.getInstance();
        right.setTime(createDate);
        right.add(Calendar.MONTH, 1);
        Date endDate = right.getTime();
        String endTime = VtuzxUtil.formatYmdHmsF(endDate);

        String mainDepartName = "";//部门名称
        String salesManId = "";//金蝶业务员id
        if (!VtuzxUtil.isEmpty(seller)) {
            String sellerName = seller.substring(0, seller.indexOf('('));//业务员姓名
            //根据姓名查询业务员所属部门
            VtuzxMap sellerMap = jiKeYunApiService.getSeller(storeDoc,
                    new VtuzxMap("realNames", sellerName));//员工姓名

            Map<String, Object> sellResult = VtuzxUtil.getObject(sellerMap, "result");
            List<Map<String, Object>> sellData = VtuzxUtil.getObject(sellResult, "data");
            Map<String, Object> sellDoc = sellData.get(0);
            mainDepartName = (String) sellDoc.get("mainDepartName");
            //查询业务员id
            //查询发货部门id
            String cond = String.format("FName = '%s'", sellerName);
            List<VtuzxMap> bd_operator = kingdeeService.query(client, "BD_OPERATOR", new VtuzxArrayList<>(
                    "FNumber",//=业务员编码
                    "FNAME"//业务员名称
            ), cond);
            if (bd_operator != null && bd_operator.size() > 0) {//如果有这个客户的话
                salesManId = (String) bd_operator.get(0).get("FNumber");
            }

        }
        String deliveryDeptId = "";//发货部门id
        if (!VtuzxUtil.isEmpty(mainDepartName)) {//如果吉客云部门名称不为空，查询金蝶部门id
            //查询发货部门id
            String cond = String.format("FName = '%s' and FForbidStatus ='%s'", mainDepartName, "A");
            List<VtuzxMap> bd_department = kingdeeService.query(client, "BD_Department", new VtuzxArrayList<>(
                    "FNumber",//=部门编码
                    "FNAME"//部门
            ), cond);
            if (bd_department != null && bd_department.size() > 0) {//如果有这个客户的话
                deliveryDeptId = (String) bd_department.get(0).get("FNumber");
            }
        }

        //查询销售单出库时间
        VtuzxMap saleOutMap = jiKeYunApiService.getStorageOut(storeDoc,
                new VtuzxMap("pageSize", 1)
                        .append("selelctFields", "inOutDate")
                        .append("pageIndex", 0)
                        .append("startDate", createTime)
                        .append("endDate", endTime)
                        .append("billNo", tradeNo));

        Map<String, Object> saleResult = VtuzxUtil.getObject(saleOutMap, "result");
        List<Map<String, Object>> saleData = VtuzxUtil.getObject(saleResult, "data");
        String outTime = "";
        if (!VtuzxUtil.isEmpty(saleData)) {
            Map<String, Object> saleDoc = saleData.get(0);
            outTime = VtuzxUtil.getString(saleDoc, "inOutDate");//出库时间
        }

        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(tradeMap, "GoodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSCKD01_SYS"));//单据类型 标准销售出库单
        payModel.put("FDate", outTime);//单据日期
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        payModel.put("FCustomerID", new Document("FNumber", customerId));//客户
        payModel.put("FReceiverID", new Document("FNumber", customerId));//收货方
        payModel.put("FSalesManID", new Document("FNumber", salesManId));//销售员
        payModel.put("FSettleID", new Document("FNumber", customerId));//结算方
        payModel.put("FPayerID", new Document("FNumber", customerId));//付款方
        payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织
        if (!VtuzxUtil.isEmpty(deliveryDeptId)) {//如果发货部门不为空的话
            payModel.put("FDeliveryDeptID", new Document("FNumber", deliveryDeptId));//发货部门
        }
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务或费用
        payModel.put("F_XSCK_JKYDJH", tradeNo);//吉客云销售单号
        payModel.put("F_ora_disFee", discountFee);//整单优惠
        payModel.put("F_ora_appendMemo", appendMemo);//追加备注
        payModel.put("F_ora_saleFee", otherFee);//销售费用
//        payModel.put("F_ora_kefuMemo",sellerMemo);//客服备注
        payModel.put("F_ora_kehuMemo", buyerMemo);//客户备注
        payModel.put("F_ora_lineTradeNo", onlineTradeNo);//网店单号
        payModel.put("F_PSUH_biaoji", flagNames);//标记
        payModel.put("F_ora_couponFee", couponFee);//平台补贴

        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FIsIncludedTax", true);//是否含税
        SubHeadEntity.put("FLocalCurrID", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率
        SubHeadEntity.put("FIsPriceExcludeTax", true);//价外税
        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        //循环货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double taxRate = VtuzxUtil.getDouble(tradeOrder, "TaxFee");//税率
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "SellPrice");//结算金额（单价）
                        int skuCount = VtuzxUtil.getInt(tradeOrder, "SellCount");//数量
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");//是否赠品
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");


                        //判断是否启用批号(单位编码)
                        String floatCond = String.format("FNumber = '%s'", goodsNo);
                        List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                "FIsBatchManage",
                                "FMATERIALID"
                        ), floatCond);
                        //获取单位编码
                        boolean flag = true;
                        String materialId = "";//物料编码id
                        if (bd_Material != null && bd_Material.size() > 0) {
                            flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                            materialId = bd_Material.get(0).getString("FMATERIALID");
                        }
                        //查询仓库(通过即时库存)
                        String inventoryCond = String.format("FMaterialId = '%s' and FBaseQty > '%d'", materialId, 0);
                        List<VtuzxMap> bd_inventory = kingdeeService.query(client, "STK_Inventory", new VtuzxArrayList<>(
                                "FStockId",
                                "FMaterialId",
                                "FLot",
                                "FBaseQty"
                        ), inventoryCond);

                        List<VtuzxMap> colMapList = new ArrayList<>();
                        for (VtuzxMap inventoryMap : bd_inventory) {
                            double residue = VtuzxUtil.getDouble(inventoryMap, "FBaseQty");
                            if (residue >= skuCount) {
                                inventoryMap.replace("FBaseQty", skuCount);
                                colMapList.add(inventoryMap);
                                break;
                            } else {//如果数量不够扣的话
                                skuCount -= residue;
                                colMapList.add(inventoryMap);
                            }
                        }
                        //查询单位编码，直接传文字无效
                        String cond = String.format("Fname = '%s'", unitName);
                        List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                                "FNumber",//物料编码
                                "FNAME"//物料名称
                        ), cond);
                        //获取物料编码
                        String unit = "";
                        if (bd_customer != null && bd_customer.size() > 0) {
                            unit = bd_customer.get(0).getString("FNumber");
                        }
                        for (VtuzxMap map : colMapList) {
                            Map<String, Object> colMap = new LinkedHashMap<>();
                            String stockNoId = VtuzxUtil.getString(map, "FStockId");//仓库Id
                            String flotNoId = VtuzxUtil.getString(map, "FLot");//批号id
                            double count = VtuzxUtil.getDouble(map, "FBaseQty");
                            colMap.put("FRowType", "Standard");//产品类型
                            if (isGift == 1) {//是赠品
                                colMap.put("isFree", true);
                            } else {
                                colMap.put("isFree", false);
                            }
                            colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                            colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                            colMap.put("FRealQty", count);//实发数量
                            colMap.put("FTaxPrice", settPrice);//含税单价
                            colMap.put("FIsFree", false);//是否赠品
                            colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                            colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                            String batchNo = "";
                            if (flag) {
                                String batchCond = String.format("FLOTID  = '%s'", flotNoId);
                                List<VtuzxMap> bd_batch = kingdeeService.query(client, "BD_BatchMainFile", new VtuzxArrayList<>(
                                        "FNumber"
                                ), batchCond);

                                if (bd_batch != null && bd_batch.size() > 0) {
                                    batchNo = bd_batch.get(0).getString("FNumber");
                                }
                                colMap.put("FLot", new Document("FNumber", batchNo));//批号
                            }
                            colMap.put("FEntryTaxRate", taxRate);//税率
                            //查询仓库
                            String stockId = "";
                            String stockCond = String.format("FStockId = '%s'", stockNoId);
                            List<VtuzxMap> bd_stock = kingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
                                    "FNumber"
                            ), stockCond);
                            if (bd_stock != null && bd_stock.size() > 0) {
                                stockId = bd_stock.get(0).getString("FNumber");
                            }
                            colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                            colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
//                            colMap.put("FLot", new Document("FNumber", flotNoId));//批号
                            colMap.put("FEntroynote", goodsMemo);//货品备注
                            colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                            colMap.put("FSALUNITQTY", count);//销售数量
                            colMap.put("FSALBASEQTY", count);//销售基本数量
                            colMap.put("FPRICEBASEQTY", count);//计价基本数量
                            colMap.put("FOUTCONTROL", false);//控制出库数量
                            colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                            colMap.put("FARNOTJOINQTY", count);//未关联应付数量（计价单位
                            colMap.put("FCheckDelivery", false);//发货检验
                            FEntity.add(colMap);
                        }


                    }
                }
            } else {//不是组合装的话需要判断有没有唯一码
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "SellPrice");//结算金额（单价）
                int skuCount = VtuzxUtil.getInt(doc, "SellCount");
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注

                String tradeId = VtuzxUtil.getString(doc, "SubTradeId");


                String serialNo = "";//唯一码
                if (!VtuzxUtil.isEmpty(goodsSerials)) {
                    for (Map<String, Object> serialMap : goodsSerials) {//循环唯一码集合
                        String serialTradeId = VtuzxUtil.getString(serialMap, "SubTradeId");
                        if (tradeId.equals(serialTradeId)) {
                            String jackSerialNo = VtuzxUtil.getString(serialMap, "SerialNo");
                            if (jackSerialNo.startsWith("HTTP://ZS")) {
                                StringBuilder sb = new StringBuilder(jackSerialNo.toLowerCase());
                                sb.setCharAt(49, 'Z');
                                sb.setCharAt(44, 'C');
                                serialNo = sb.toString();
                                break;
                            }
                        }
                    }

                }
                if (!VtuzxUtil.isEmpty(serialNo)) {//唯一码出库
                    //查询唯一码所在仓库
//                    Document traceabilityDoc = traceabilityCodeDetailDao.findOne(Criteria.where("traceabilityCode").is(serialNo));
//                    String boxNo = VtuzxUtil.getString(traceabilityDoc,"boxNo");
                    Document inventoryDoc = inventoryDetailDao.findOne(Criteria.where("traceBack.traceBackNo").is(serialNo));
                    String stockId = VtuzxUtil.getString(inventoryDoc, "stockNo");//仓库编码
                    //查询单位编码，直接传文字无效
                    String cond = String.format("Fname = '%s'", unitName);
                    List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                            "FNumber",//物料编码
                            "FNAME"//物料名称
                    ), cond);
                    String unit = "";
                    if (bd_customer != null && bd_customer.size() > 0) {
                        unit = bd_customer.get(0).getString("FNumber");
                    }

                    Map<String, Object> colMap = new LinkedHashMap<>();
                    colMap.put("FRowType", "Standard");//产品类型
                    if (isGift == 1) {//是赠品
                        colMap.put("isFree", true);
                    } else {
                        colMap.put("isFree", false);
                    }
                    colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                    colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                    colMap.put("FRealQty", skuCount);//实发数量
                    colMap.put("FTaxPrice", settPrice);//含税单价
                    colMap.put("FIsFree", false);//是否赠品
                    colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                    colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                    colMap.put("FEntryTaxRate", taxRate);//税率
                    colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                    colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                    colMap.put("FEntroynote", goodsMemo);//货品备注
                    colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                    colMap.put("FSALUNITQTY", skuCount);//销售数量
                    colMap.put("FSALBASEQTY", skuCount);//销售基本数量
                    colMap.put("FPRICEBASEQTY", skuCount);//计价基本数量
                    colMap.put("FOUTCONTROL", false);//控制出库数量
                    colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                    colMap.put("FARNOTJOINQTY", skuCount);//未关联应付数量（计价单位
                    colMap.put("FCheckDelivery", false);//发货检验
                    FEntity.add(colMap);
                } else {//没有唯一码出库
                    //判断是否启用批号(单位编码)
                    String floatCond = String.format("FNumber = '%s'", goodsNo);
                    List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                            "FIsBatchManage",
                            "FMATERIALID"
                    ), floatCond);
                    //获取单位编码
                    boolean flag = true;
                    String materialId = "";//物料编码id
                    if (bd_Material != null && bd_Material.size() > 0) {
                        flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                        materialId = bd_Material.get(0).getString("FMATERIALID");
                    }
                    //查询即时库存取物料仓库信息
                    String inventoryCond = String.format("FMaterialId = '%s' and FBaseQty > '%d'", materialId, 0);
                    List<VtuzxMap> bd_inventory = kingdeeService.query(client, "STK_Inventory", new VtuzxArrayList<>(
                            "FStockId",
                            "FMaterialId",
                            "FLot",
                            "FBaseQty"
                    ), inventoryCond);

                    List<VtuzxMap> colMapList = new ArrayList<>();
                    for (VtuzxMap inventoryMap : bd_inventory) {
                        double residue = VtuzxUtil.getDouble(inventoryMap, "FBaseQty");
                        if (residue >= skuCount) {
                            inventoryMap.replace("FBaseQty", skuCount);
                            colMapList.add(inventoryMap);
                            break;
                        } else {//如果数量不够扣的话
                            skuCount -= residue;
                            colMapList.add(inventoryMap);
                        }
                    }


                    //查询单位编码，直接传文字无效
                    String cond = String.format("Fname = '%s'", unitName);
                    List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                            "FNumber",//物料编码
                            "FNAME"//物料名称
                    ), cond);
                    String unit = "";
                    if (bd_customer != null && bd_customer.size() > 0) {
                        unit = bd_customer.get(0).getString("FNumber");
                    }
                    for (VtuzxMap map : colMapList) {
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        String stockNoId = VtuzxUtil.getString(map, "FStockId");//仓库Id
                        String flotNoId = VtuzxUtil.getString(map, "FLot");//批号id
                        double count = VtuzxUtil.getDouble(map, "FBaseQty");
                        colMap.put("FRowType", "Standard");//产品类型
                        if (isGift == 1) {//是赠品
                            colMap.put("isFree", true);
                        } else {
                            colMap.put("isFree", false);
                        }
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", count);//实发数量
                        colMap.put("FTaxPrice", settPrice);//含税单价
                        colMap.put("FIsFree", false);//是否赠品
                        colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                        colMap.put("FOWNERID", new Document("FNumber", "100"));//货主开发销售测试
                        String batchNo = "";
                        if (flag) {
                            String batchCond = String.format("FLOTID  = '%s'", flotNoId);
                            List<VtuzxMap> bd_batch = kingdeeService.query(client, "BD_BatchMainFile", new VtuzxArrayList<>(
                                    "FNumber"
                            ), batchCond);

                            if (bd_batch != null && bd_batch.size() > 0) {
                                batchNo = bd_batch.get(0).getString("FNumber");
                            }
                            colMap.put("FLot", new Document("FNumber", batchNo));//批号
                        }
                        colMap.put("FEntryTaxRate", taxRate);//税率
                        //查询仓库
                        String stockId = "";
                        String stockCond = String.format("FStockId = '%s'", stockNoId);
                        List<VtuzxMap> bd_stock = kingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
                                "FNumber"
                        ), stockCond);
                        if (bd_stock != null && bd_stock.size() > 0) {
                            stockId = bd_stock.get(0).getString("FNumber");
                        }
                        colMap.put("FStockId", new Document("FNumber", stockId));//仓库
                        colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态

                        colMap.put("FEntroynote", goodsMemo);//货品备注
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSALUNITQTY", count);//销售数量
                        colMap.put("FSALBASEQTY", count);//销售基本数量
                        colMap.put("FPRICEBASEQTY", count);//计价基本数量
                        colMap.put("FOUTCONTROL", false);//控制出库数量
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", count);//未关联应付数量（计价单位
                        colMap.put("FCheckDelivery", false);//发货检验
                        FEntity.add(colMap);
                    }

                }


            }
        }
        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        historyDoc.append("param", payModel);
        //创建销售出库单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_OUTSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(tradeNo + e.getMessage());
//            throw new VtuzxException(e.getMessage());
        }


    }

    //晓芹销售退(销售单)
    private void syncKingdeeSaleReturnXQ(VtuzxKingdeeCloudClient client, VtuzxMap data, Document historyDoc) throws Exception {
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerId = "";//传金蝶的客户编号
        //先判断客户是否加密
        VtuzxMap customerMap = jiKeYunApiService.customerList(storeDoc,
                new VtuzxMap("customerCode", customerCode));//客户编号

        Map<String, Object> customerResult = VtuzxUtil.getObject(customerMap, "result");
        List<Map<String, Object>> customerData = VtuzxUtil.getObject(customerResult, "data");
        Map<String, Object> customerDoc = customerData.get(0);

        String nickName = VtuzxUtil.getString(customerDoc, "nickname");
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(nickName);
        if ((!m.find() && nickName.length() > 8) || VtuzxUtil.isEmpty(nickName)) {//说明是加密的
            customerId = "CUST0043";//加密的客户固定
        } else {//没加密先去金蝶查询是否存在，不存在做新增
            //查询客户
            String cond = String.format("FNumber = '%s'", customerCode);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                    "FNumber",//客户编码
                    "FNAME"//客户名称
            ), cond);
            if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                customerId = customerCode;
            } else {//没有的话做新增
                String telephone = VtuzxUtil.getString(customerMap, "phone");
                Map<String, Object> model = new LinkedHashMap<>();
                model.put("FCUSTID", 0);
                model.put("FCreateOrgId", new Document("FNumber", "100"));
                model.put("FNumber", customerCode);//客户编码
                model.put("FUseOrgId", new Document("FNumber", "100"));//使用组织
                model.put("FName", nickName);//客户姓名
                model.put("FCOUNTRY", new Document("FNumber", "China"));
                model.put("FTEL", telephone);
                model.put("FINVOICETITLE", nickName);//发票抬头
                model.put("FIsGroup", false);//集团客户
                model.put("FIsDefPayer", false);//默认付款方
                model.put("FCustTypeId", new Document("FNumber", "KHLB001_SYS"));//客户类别
                //TODO
                model.put("FGroup", new Document("FNumber", "01"));//客户分组
                model.put("FTRADINGCURRID", new Document("FNumber", "PRE001"));//结算币别
                model.put("FInvoiceType", "1");//发票类型
                model.put("FTaxType", new Document("FNumber", "SFL02_SYS"));//税分类
                model.put("FPriority", "1");//客户优先级
                model.put("FTaxRate", new Document("FNumber", "SL02_SYS"));//默认税率
                model.put("FISCREDITCHECK", true);//启用信用管理
                model.put("FIsTrade", true);//是否交易客户
                model.put("FUncheckExpectQty", false);//不校验可发量
                Map<String, Object> customerext = new LinkedHashMap<>();//商务信息
                customerext.put("FEnableSL", false);//启用商联在线
                customerext.put("FALLOWJOINZHJ", false);//允许对接智慧订货
                model.put("FT_BD_CUSTOMEREXT", customerext);
                Map<String, Object> kneeParam = new LinkedHashMap<>();
                kneeParam.put("NeedUpDateFields", new ArrayList<>());
                kneeParam.put("NeedReturnFields", new ArrayList<>());
                kneeParam.put("IsDeleteEntry", true);
                kneeParam.put("SubSystemId", "");
                kneeParam.put("IsVerifyBaseDataField", true);
                kneeParam.put("IsEntryBatchFill", false);
                kneeParam.put("ValidateFlag", true);
                kneeParam.put("NumberSearch", true);
                kneeParam.put("IsAutoAdjustField", false);
                kneeParam.put("InterationFlags", "");
                kneeParam.put("IgnoreInterationFlag", "");
                kneeParam.put("IsControlPrecision", false);
                kneeParam.put("ValidateRepeatJson", false);
                kneeParam.put("Model", model);
                try {
                    List<VtuzxMap> customerList = kingdeeService.save(client, "BD_Customer", kneeParam);
                    VtuzxMap kingdeeCustomerMap = customerList.get(0);
                    String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
                    kingdeeService.submit(client, "BD_Customer", "0", number);
                    kingdeeService.audit(client, "BD_Customer", "0", number, "STK_InvCheckResult");
                    customerId = customerCode;
                } catch (Exception e) {
                    _logger.info(e.getMessage());
                }
            }
        }

        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号
        VtuzxMap saleMap = jiKeYunApiService.getSaleBill(storeDoc,
                new VtuzxMap()
                        .append("tradeNo", tradeNo)
                        .append("pageSize", 50)
                        .append("pageIndex", 0)
                        .append("fields", "couponFee,gmtCreate,seller,onlineTradeNo,appendMemo,buyerMemo,sellerMemo,otherFee,discountFee,isFit,isGift,goodsMemo,tradeFrom,consignTime,goodsSerial.subTradeId,goodsSerial.skuId,goodsSerial.serialNo,warehouseName,warehouseCode,customerCode,goodsDetail.goodsNo,goodsDelivery.productionDate,goodsDelivery.expirationDate,goodsDelivery.batchNo,tradeNo,tradeStatus,warehouseCode,shopName,flagIds,sysFlagIds,flagNames,tradeCount,shareFavourableFee,warehouseCode,goodsDetail.unit,goodsDetail.goodsNo,goodsDetail.goodsName,goodsDetail.specName,goodsDetail.sellCount,goodsDetail.sellPrice,goodsDetail.taxRate,sellerMemo,goodsDelivery.batchNo,goodsSerial.serialNo"));

        Map<String, Object> tradeResult = VtuzxUtil.getObject(saleMap, "result");

        String tradeString = VtuzxUtil.getString(tradeResult, "data");
        Map<String, Object> tradeData = JSON.parseObject(tradeString, new TypeReference<HashMap<String, Object>>() {
        });
        JSONArray jsonArray = VtuzxUtil.getObject(tradeData, "Trades");
        JSONObject jsonTrades = (JSONObject) jsonArray.get(0);
        Map<String, Object> tradeMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : jsonTrades.entrySet()) {
            tradeMap.put(entry.getKey(), entry.getValue());
        }

        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(tradeMap, "TradeOrderAssemblyGoodsDtoList");//组合装信息
        List<Map<String, Object>> goodsSerials = VtuzxUtil.getObject(tradeMap, "GoodsSerials");//唯一码集合
        double otherFee = VtuzxUtil.getDouble(tradeMap, "OtherFee");//销售费用
        double discountFee = VtuzxUtil.getDouble(tradeMap, "DiscountFee");//整单优惠
        double couponFee = VtuzxUtil.getDouble(tradeMap, "CouponFee");//平台补贴(平台优惠)
        String sellerMemo = VtuzxUtil.getString(tradeMap, "SellerMemo");//备注(客服备注)
        String buyerMemo = VtuzxUtil.getString(tradeMap, "BuyerMemo");//(买家备注)客户备注
        String appendMemo = VtuzxUtil.getString(tradeMap, "AppendMemo");//追加备注
        String onlineTradeNo = VtuzxUtil.getString(tradeMap, "OnlineTradeNo");//网店订单号
        String seller = VtuzxUtil.getString(tradeMap, "Seller");//业务员
        String flagNames = VtuzxUtil.getString(tradeMap, "FlagNames");//标记名称
        String createTime = VtuzxUtil.getString(tradeMap, "GmtCreate");//创建日期
        Date createDate = VtuzxUtil.parseDate(createTime);
        Calendar right = Calendar.getInstance();
        right.setTime(createDate);
        right.add(Calendar.MONTH, 1);
        Date endDate = right.getTime();
        String endTime = VtuzxUtil.formatYmdHmsF(endDate);

        String mainDepartName = "";//部门名称
        String salesManId = "";//金蝶业务员id
        if (!VtuzxUtil.isEmpty(seller)) {
            String sellerName = seller.substring(0, seller.indexOf('('));//业务员姓名
            //根据姓名查询业务员所属部门
            VtuzxMap sellerMap = jiKeYunApiService.getSeller(storeDoc,
                    new VtuzxMap("realNames", sellerName));//员工姓名

            Map<String, Object> sellResult = VtuzxUtil.getObject(sellerMap, "result");
            List<Map<String, Object>> sellData = VtuzxUtil.getObject(sellResult, "data");
            Map<String, Object> sellDoc = sellData.get(0);
            mainDepartName = (String) sellDoc.get("mainDepartName");
            //查询业务员id
            //查询发货部门id
            String cond = String.format("FName = '%s'", sellerName);
            List<VtuzxMap> bd_operator = kingdeeService.query(client, "BD_OPERATOR", new VtuzxArrayList<>(
                    "FNumber",//=业务员编码
                    "FNAME"//业务员名称
            ), cond);
            if (bd_operator != null && bd_operator.size() > 0) {//如果有这个客户的话
                salesManId = (String) bd_operator.get(0).get("FNumber");
            }

        }
        String deliveryDeptId = "";//发货部门id
        if (!VtuzxUtil.isEmpty(mainDepartName)) {//如果吉客云部门名称不为空，查询金蝶部门id
            //查询发货部门id
            String cond = String.format("FName = '%s' and FForbidStatus ='%s'", mainDepartName, "A");
            List<VtuzxMap> bd_department = kingdeeService.query(client, "BD_Department", new VtuzxArrayList<>(
                    "FNumber",//=部门编码
                    "FNAME"//部门
            ), cond);
            if (bd_department != null && bd_department.size() > 0) {//如果有这个客户的话
                deliveryDeptId = (String) bd_department.get(0).get("FNumber");
            }
        }

        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(tradeMap, "GoodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型 标准销售退货单
        payModel.put("FDate", createTime);//单据日期
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        payModel.put("FRetcustId", new Document("FNumber", customerId));//退货客户
        payModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        payModel.put("FStockOrgId", new Document("FNumber", "100"));//库存组织
        payModel.put("FReceiveCustId", new Document("FNumber", customerId));//收货方
        payModel.put("FSettleCustId", new Document("FNumber", customerId));//结算方
        payModel.put("FPayCustId", new Document("FNumber", customerId));//付款方
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务标识
        payModel.put("F_XSTH_JKYDJH", tradeNo);//金蝶单号


        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率

        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        //循环货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "subTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "subTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double taxRate = VtuzxUtil.getDouble(tradeOrder, "TaxFee");//税率
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "SellPrice");//结算金额（单价）
                        int skuCount = VtuzxUtil.getInt(tradeOrder, "SellCount");//数量
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");//是否赠品
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");


                        //判断是否启用批号(单位编码)
                        String floatCond = String.format("FNumber = '%s'", goodsNo);
                        List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                "FIsBatchManage",
                                "FMATERIALID"
                        ), floatCond);
                        //获取单位编码
                        boolean flag = true;
                        String materialId = "";//物料编码id
                        if (bd_Material != null && bd_Material.size() > 0) {
                            flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                            materialId = bd_Material.get(0).getString("FMATERIALID");
                        }
                        //查询仓库(通过即时库存)
                        String inventoryCond = String.format("FMaterialId = '%s' and FBaseQty > '%d'", materialId, 0);
                        List<VtuzxMap> bd_inventory = kingdeeService.query(client, "STK_Inventory", new VtuzxArrayList<>(
                                "FStockId",
                                "FMaterialId",
                                "FLot",
                                "FBaseQty"
                        ), inventoryCond);

                        List<VtuzxMap> colMapList = new ArrayList<>();
                        for (VtuzxMap inventoryMap : bd_inventory) {
                            double residue = VtuzxUtil.getDouble(inventoryMap, "FBaseQty");
                            if (residue >= skuCount) {
                                inventoryMap.replace("FBaseQty", skuCount);
                                colMapList.add(inventoryMap);
                                break;
                            } else {//如果数量不够扣的话
                                skuCount -= residue;
                                colMapList.add(inventoryMap);
                            }
                        }
                        //查询单位编码，直接传文字无效
                        String cond = String.format("Fname = '%s'", unitName);
                        List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                                "FNumber",//物料编码
                                "FNAME"//物料名称
                        ), cond);
                        //获取物料编码
                        String unit = "";
                        if (bd_customer != null && bd_customer.size() > 0) {
                            unit = bd_customer.get(0).getString("FNumber");
                        }
                        for (VtuzxMap map : colMapList) {
                            Map<String, Object> colMap = new LinkedHashMap<>();
                            String stockNoId = VtuzxUtil.getString(map, "FStockId");//仓库Id
                            String flotNoId = VtuzxUtil.getString(map, "FLot");//批号id
                            double count = VtuzxUtil.getDouble(map, "FBaseQty");
                            count = Math.abs(count);
                            colMap.put("FRowType", "Standard");//产品类型
                            colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                            colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                            colMap.put("FRealQty", count);//实退数量
                            colMap.put("FTaxPrice", settPrice);//含税单价
                            if (isGift == 1) {//是赠品
                                colMap.put("isFree", true);
                            } else {
                                colMap.put("isFree", false);
                            }
                            colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                            colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                            colMap.put("FOwnerId", new Document("FNumber", "100"));//货主开发销售测试
                            colMap.put("FStockId", new Document("FNumber", "034"));//仓库售后退货仓
                            colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                            if (flag) {
                                colMap.put("FLot", new Document("FNumber", "11111"));//批号
                            }
                            colMap.put("FDeliveryDate", createTime);//退货日期
                            colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                            colMap.put("FSalUnitQty", count);//销售数量
                            colMap.put("FSalBaseQty", count);//销售基本数量
                            colMap.put("FPriceBaseQty", count);//计价基本数量
                            colMap.put("FEntryTaxRate", taxRate);//税率
                            colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                            colMap.put("FARNOTJOINQTY", count);//未关联应收数量（计价单位
                            colMap.put("FIsReturnCheck", false);//发货检验
                            colMap.put("FNote ", goodsMemo);//货品备注

                            FEntity.add(colMap);
                        }


                    }
                }
            } else {//不是组合装的退货
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double taxRate = VtuzxUtil.getDouble(doc, "TaxFee");//税率
                double settPrice = VtuzxUtil.getDouble(doc, "SellPrice");//结算金额（单价）
                int skuCount = VtuzxUtil.getInt(doc, "SellCount");
                skuCount = Math.abs(skuCount);
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注

                //判断是否启用批号(单位编码)
                String floatCond = String.format("FNumber = '%s'", goodsNo);
                List<VtuzxMap> bd_Material = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FIsBatchManage",
                        "FMATERIALID"
                ), floatCond);
                //获取单位编码
                boolean flag = true;
                if (bd_Material != null && bd_Material.size() > 0) {
                    flag = bd_Material.get(0).getBoolean("FIsBatchManage");
                }

                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                        "FNumber",//物料编码
                        "FNAME"//物料名称
                ), cond);
                String unit = "";
                if (bd_customer != null && bd_customer.size() > 0) {
                    unit = bd_customer.get(0).getString("FNumber");
                }
                Map<String, Object> colMap = new LinkedHashMap<>();

                colMap.put("FRowType", "Standard");//产品类型
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", skuCount);//实退数量
                colMap.put("FTaxPrice", settPrice);//含税单价
                if (isGift == 1) {//是赠品
                    colMap.put("isFree", true);
                } else {
                    colMap.put("isFree", false);
                }
                colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                colMap.put("FOwnerId", new Document("FNumber", "100"));//货主开发销售测试
                colMap.put("FStockId", new Document("FNumber", "034"));//仓库售后退货仓
                colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                if (flag) {
                    colMap.put("FLot", new Document("FNumber", "11111"));//批号
                }
                colMap.put("FDeliveryDate", createTime);//退货日期
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSalUnitQty", skuCount);//销售数量
                colMap.put("FSalBaseQty", skuCount);//销售基本数量
                colMap.put("FPriceBaseQty", skuCount);//计价基本数量
                colMap.put("FEntryTaxRate", taxRate);//税率
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
                colMap.put("FIsReturnCheck", false);//发货检验
                colMap.put("FNote ", goodsMemo);//货品备注
                FEntity.add(colMap);
            }
        }
        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", false);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        historyDoc.append("param", payModel);
        //创建晓芹销售退货单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            _logger.info(tradeNo + e.getMessage());
            throw new VtuzxException(e.getMessage());
        }


    }

    //野象销售退(销售单)
    private void syncKingdeeSaleReturnYX(VtuzxKingdeeCloudClient client, VtuzxMap data, Document historyDoc) throws Exception {
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data, "customerName");//客户名称
        String customerId = getCustomer(customerCode, client, storeDoc, customerName);
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号
        String orderTime = VtuzxUtil.getString(historyDoc, "orderTime");//单据日期
        String onLineTradeNo = VtuzxUtil.getString(data, "onLineTradeNo");//网店订单号
        String shopName = VtuzxUtil.getString(data, "shopName");//店铺名称


        if ("bb044山东路专卖店-野象".equals(shopName)) {
            shopName = "bb045山东路专卖店-野象";
        }
        //外埠的不要做截取,还有门店的
        if (shopName.contains("-") && !shopName.contains("外埠") && !shopName.startsWith("bb") && !shopName.contains("展示厅") && !shopName.contains("天猫") && !shopName.startsWith("百年晓芹")) {
            shopName = shopName.substring(0, shopName.indexOf("-"));
        }

        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息

        String seller = VtuzxUtil.getString(data, "seller");//业务员
        String createTime = VtuzxUtil.getString(data, "gmtCreate");//创建日期
        String warehouseName = VtuzxUtil.getString(data, "warehouseName");//仓库对应销售渠道
        //同步数据时会同步部门,后加的
        String departName = VtuzxUtil.getString(data, "departName");//部门

        //渠道是爱你商城传金蝶部门为市场部，客户为爱你商城
        if ("爱你商城".equals(shopName)) {
            departName = "市场部";
        }
        if (departName.contains("外埠")) {//如果部门为外埠固定传(因为吉客云和金蝶部门名称没统一)
            departName = "外埠（营销外埠）";
        } else if (departName.contains("网购") || departName.contains("营销三部")) {
            departName = "网购（营销网购）";
        } else if (departName.contains("bb044")) {
            departName = "bb045山东路专卖店";
        }
        //查询部门的时候加上禁用状态
        String deliveryDeptId = "";//发货部门id
        String qdNo = "";//渠道编号
        if (!VtuzxUtil.isEmpty(departName)) {//如果吉客云部门名称不为空，查询金蝶部门id
            //查询发货部门id
            String cond = String.format("FName = '%s' and FForbidStatus ='%s'", departName, "A");
            List<VtuzxMap> bd_department = kingdeeService.query(client, "BD_Department", new VtuzxArrayList<>(
                    "FNumber",//=部门编码
                    "FNAME"//部门
            ), cond);
            if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                deliveryDeptId = (String) bd_department.get(0).get("FNumber");
            }

            //查询客户
            String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", departName, "A");
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                    "FNumber",//客户编码
                    "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                    "FNAME"//客户名称
            ), cusCond);
            if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                qdNo = VtuzxUtil.getString(bd_customer.get(0), "F_SXLJ_xsqd.FNUMBER");
            }
        }
        //如果发货部门为空的话不让传
        if (VtuzxUtil.isEmpty(deliveryDeptId)) {
            historyDoc.append("message", "无法查询到部门,请维护");
            throw new VtuzxException("无法查询到部门,请维护");
        }

        //在同步单据的时候会查询仓库id
        //存在没有仓库的情况,给与提示
        String stockId = VtuzxUtil.getString(data, "stockId");
        if (VtuzxUtil.isEmpty(stockId)) {
            historyDoc.append("message", "没有获取到仓库id,请重新同步单据");
            throw new VtuzxException("没有获取到仓库id,请重新同步单据");
        }
        //如果是门店的渠道截取一下，因为金蝶上没有-后面的信息
        if (shopName.startsWith("bb")) {
            shopName = shopName.substring(0, shopName.indexOf("-"));
        }
        //门店的通过部门查询
        String shopCustomerId = "";
        if (shopName.startsWith("bb")) {
            shopCustomerId = getCustomerShopName(client, departName);
        } else {
            //添加门店渠道中的对应关系
            if ("野象考拉店铺".equals(shopName)) {
                shopName = "网易考拉";
            } else if ("野象苏宁超市".equals(shopName)) {
                shopName = "苏宁超市";
            } else if ("客服外卖-代收货款".equals(shopName)) {
                shopName = "客服外卖";
            } else if ("野象-展示厅".equals(shopName)) {
                shopName = "展示厅";
            } else if ("天猫超市-野象".equals(shopName)) {
                shopName = "天猫超市";
            } else if ("杭州光年有限公司".equals(shopName)) {
                shopName = "光年（杭州）水产品";
            } else if ("天猫旗舰店-野象".equals(shopName)) {
                shopName = "天猫商城";
            } else if ("百年晓芹-拼多多生鲜".equals(shopName)) {
                shopName = "拼多多-生鲜";
            }
            shopCustomerId = getCustomerShopName(client, shopName);
        }

        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        payModel.put("FDate", orderTime);//单据日期
//        payModel.put("FDate", VtuzxUtil.formatYmdHmsF(new Date()));//单据日期
        //门店的发货组织还是100
        if (shopName.startsWith("bb")) {
            payModel.put("FStockOrgId", new Document("FNumber", "100"));//发货组织
        } else {
            payModel.put("FStockOrgId", new Document("FNumber", "200"));//发货组织
        }

        //如果是外埠的客户还是正常客户
        if ("外埠".equals(channelGroup)) {
            payModel.put("FRetcustId", new Document("FNumber", customerId));//退货客户
            payModel.put("FReceiveCustId", new Document("FNumber", customerId));//收货方
            payModel.put("FSettleCustId", new Document("FNumber", customerId));//结算方
            payModel.put("FPayCustId", new Document("FNumber", customerId));//付款方
        } else {//其他的传渠道信息
            payModel.put("FRetcustId", new Document("FNumber", shopCustomerId));//退货客户
            payModel.put("FReceiveCustId", new Document("FNumber", shopCustomerId));//收货方
            payModel.put("FSettleCustId", new Document("FNumber", shopCustomerId));//结算方
            payModel.put("FPayCustId", new Document("FNumber", shopCustomerId));//付款方
        }
        payModel.put("FSaledeptid", new Document("FNumber", deliveryDeptId));//销售部门
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型 标准销售退货单

        payModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务标识
        payModel.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
        payModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        payModel.put("F_PSUH_DPMC", shopName);//店铺名称
        payModel.put("F_ora_lineTradeNo", onLineTradeNo);//网店订单号
        payModel.put("F_PSUH_KHMC", customerName);//客户名称
        payModel.put("F_SXLJ_JKYKHBH", customerCode);//客户编号
        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率

        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        List<String> materialNoList = new ArrayList<>();
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);

        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            //存在零税率的增值税
            String substring = "";
            if (fTaxRateName.indexOf("%") > 0) {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            } else {
                substring = "0";
            }

            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //循环整理后的货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "SellTotal");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        skuCount = Math.abs(skuCount);
                        settPrice = Math.abs(settPrice);
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        String unit = (String) unitMap.get(unitName);
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");//产品类型
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", skuCount);//实退数量
                        colMap.put("FTaxPrice", settPrice / skuCount);//含税单价
                        if (settPrice / skuCount == 0) {//是赠品
                            colMap.put("FIsFree", true);
                        } else {
                            colMap.put("FIsFree", false);
                        }
                        colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                        colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                        //门店的货主也是100
                        if (shopName.startsWith("bb")) {
                            colMap.put("FOwnerId", new Document("FNumber", "100"));//货主开发销售测试
                            colMap.put("FStockId", new Document("FNumber", stockId));
                        } else {
                            colMap.put("FOwnerId", new Document("FNumber", "200"));//货主开发销售测试
                            colMap.put("FStockId", new Document("FNumber", "001"));
                        }

                        colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态

                        colMap.put("FDeliveryDate", createTime);//退货日期
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSalUnitQty", skuCount);//销售数量
                        colMap.put("FSalBaseQty", skuCount);//销售基本数量
                        colMap.put("FPriceBaseQty", skuCount);//计价基本数量
                        //获取税率信息
                        //double tax = (double) taxMap.get(goodsNo);
                        //colMap.put("FEntryTaxRate", tax);//税率
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
                        colMap.put("FIsReturnCheck", false);//发货检验
                        colMap.put("FNote", goodsMemo);//货品备注
                        colMap.put("F_PSUH_QD", new Document("FNumber", qdNo));//渠道
                        FEntity.add(colMap);

                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double settPrice = Math.abs(VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee"));//分摊后金额,对应金蝶含税单价
                double skuCount = Math.abs(VtuzxUtil.getDouble(doc, "SellCount"));
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String unit = (String) unitMap.get(unitName);
                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");//产品类型
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                //colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", skuCount);//实退数量
                colMap.put("FTaxPrice", settPrice / skuCount);//含税单价 = 分摊后金额 / 数量
                if (settPrice / skuCount == 0) {//是赠品
                    colMap.put("FIsFree", true);
                } else {
                    colMap.put("FIsFree", false);
                }
                colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                //门店的货主也是100
                if (shopName.startsWith("bb")) {
                    colMap.put("FOwnerId", new Document("FNumber", "100"));//货主开发销售测试
                    colMap.put("FStockId", new Document("FNumber", stockId));
                } else {
                    colMap.put("FOwnerId", new Document("FNumber", "200"));//货主开发销售测试
                    colMap.put("FStockId", new Document("FNumber", "001"));
                }
                colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态

                colMap.put("FDeliveryDate", createTime);//退货日期
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSalUnitQty", skuCount);//销售数量
                colMap.put("FSalBaseQty", skuCount);//销售基本数量
                colMap.put("FPriceBaseQty", skuCount);//计价基本数量
                //获取税率信息
                //double tax = (double) taxMap.get(goodsNo);
                //colMap.put("FEntryTaxRate", tax);//税率
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
                colMap.put("FIsReturnCheck", false);//发货检验
                colMap.put("FNote ", goodsMemo);//货品备注
                colMap.put("F_PSUH_QD", new Document("FNumber", qdNo));//渠道
                FEntity.add(colMap);
            }
        }

        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", true);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        historyDoc.append("param", payModel);
        //创建销售退货单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            //如果是因为关账日期的,修改关账日期重新上传
            if (e.getMessage().contains("货主组织已关账")) {
                //如果是因为关账原因没有上传成功的需要重新上传,日期为下个月的第一天
                String closeTime = e.getMessage().substring(48, 58);
                Date closeDate = VtuzxUtil.parseDate(closeTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(closeDate);
                calendar.add(Calendar.MONTH, 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);//当月第一天
                Date time = calendar.getTime();
                String firstTime = VtuzxUtil.formatYmdHmsF(time);
                syncKingdeeSaleRefoundOneAccount(client, data, historyDoc, storeDoc, firstTime);
            } else {
                _logger.info(tradeNo + e.getMessage());
                throw new VtuzxException(e.getMessage());
            }

        }


    }

    /**
     * 野象销售退(因为关账日期的重新上传)
     *
     * @param client
     * @param data
     * @param historyDoc
     * @param storeDoc
     * @param firstTime
     */
    private void syncKingdeeSaleRefoundOneAccount(VtuzxKingdeeCloudClient client, VtuzxMap data, Document historyDoc, Document storeDoc, String firstTime) throws Exception {

        String customerCode = VtuzxUtil.getString(data, "customerCode");//客户编号
        String customerName = VtuzxUtil.getString(data, "customerName");//客户名称
        String customerId = getCustomer(customerCode, client, storeDoc, customerName);
        String tradeNo = VtuzxUtil.getString(data, "tradeNo");//销售单号
        String onLineTradeNo = VtuzxUtil.getString(data, "onLineTradeNo");//网店订单号
        String shopName = VtuzxUtil.getString(data, "shopName");//店铺名称
        //查询渠道分组
        Document channelDoc = channelDao.findOne(Criteria.where("channelName").is(shopName));
        String channelGroup = VtuzxUtil.getString(channelDoc, "channelGroup");//渠道分组(销售渠道)
        List<Map<String, Object>> tradeOrderAssemblyGoodsDtoList = VtuzxUtil.getObject(data, "tradeOrderAssemblyGoodsDtoList");//组合装信息

        String seller = VtuzxUtil.getString(data, "seller");//业务员
        String createTime = VtuzxUtil.getString(data, "gmtCreate");//创建日期
        String warehouseName = VtuzxUtil.getString(data, "warehouseName");//仓库对应销售渠道


        List<Map<String, Object>> goodsList = VtuzxUtil.getObject(data, "goodsDetail");
        Map<String, Object> payModel = new LinkedHashMap<>();//金蝶销售出model
        payModel.put("FID", 0);//实体主键
        payModel.put("FBillTypeID", new Document("FNUMBER", "XSTHD01_SYS"));//单据类型 标准销售退货单
        payModel.put("FDate", firstTime);//单据日期
        payModel.put("FSaleOrgId", new Document("FNumber", "100"));//销售组织
        payModel.put("FRetcustId", new Document("FNumber", customerId));//退货客户
        payModel.put("FTransferBizType", new Document("FNumber", "OverOrgSal"));//跨组织业务类型
        payModel.put("FStockOrgId", new Document("FNumber", "100"));//库存组织
        payModel.put("FReceiveCustId", new Document("FNumber", customerId));//收货方
        payModel.put("FSettleCustId", new Document("FNumber", customerId));//结算方
        payModel.put("FPayCustId", new Document("FNumber", customerId));//付款方
        payModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        payModel.put("FIsTotalServiceOrCost", false);//整单服务标识
        payModel.put("F_PSUH_XSDH", tradeNo);//吉客云销售单号
        payModel.put("F_PSUH_XSQD", channelGroup);//销售渠道
        payModel.put("F_PSUH_DPMC", shopName);//店铺名称
        payModel.put("F_ora_lineTradeNo", onLineTradeNo);//网店订单号
        payModel.put("F_PSUH_KHMC", customerName);//客户名称
        payModel.put("F_SXLJ_JKYKHBH", customerCode);//客户编号
        Map<String, Object> SubHeadEntity = new LinkedHashMap<>();//财务信息参数
        SubHeadEntity.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别 人民币
        SubHeadEntity.put("FSettleOrgID", new Document("FNumber", "100"));//结算组织
        SubHeadEntity.put("FLocalCurrId", new Document("FNumber", "PRE001"));//本位币
        SubHeadEntity.put("FExchangeTypeID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        SubHeadEntity.put("FExchangeRate", 1.0);//汇率

        List<Map<String, Object>> FEntity = new ArrayList<>();//销售出库体数据
        List<String> materialNoList = new ArrayList<>();
        //获取到的物料信息分散(一个品出库10个会有十条数据)整理到一起
        Map<String, Object> materialMap = arrangeMaterial(goodsList, tradeOrderAssemblyGoodsDtoList, materialNoList);
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            //存在零税率的增值税
            String substring = "";
            if (fTaxRateName.indexOf("%") > 0) {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            } else {
                substring = "0";
            }

            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //循环整理后的货品集合，添加金蝶单据体信息
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            int isFit = VtuzxUtil.getInt(doc, "IsFit");//判断是否是组合装
            if (isFit == 1) {
                String subTradeId = VtuzxUtil.getString(doc, "SubTradeId");
                //组合装的话从组合装集合里获取信息
                for (Map<String, Object> tradeOrder : tradeOrderAssemblyGoodsDtoList) {
                    String tradeSubTradeId = VtuzxUtil.getString(tradeOrder, "SubTradeId");
                    if (subTradeId.equals(tradeSubTradeId)) {
                        String goodsNo = VtuzxUtil.getString(tradeOrder, "GoodsNo");
                        String unitName = VtuzxUtil.getString(tradeOrder, "Unit");
                        double settPrice = VtuzxUtil.getDouble(tradeOrder, "ShareFavourableAfterFee");//结算金额（单价）
                        double skuCount = VtuzxUtil.getDouble(tradeOrder, "SellCount");//数量
                        skuCount = Math.abs(skuCount);
                        int isGift = VtuzxUtil.getInt(tradeOrder, "IsGift");
                        String goodsMemo = VtuzxUtil.getString(tradeOrder, "GoodsMemo");
                        //查询单位编码，直接传文字无效
                        String unit = (String) unitMap.get(unitName);
                        Map<String, Object> colMap = new LinkedHashMap<>();
                        colMap.put("FRowType", "Standard");//产品类型
                        colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                        colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                        colMap.put("FRealQty", skuCount);//实退数量
                        colMap.put("FTaxPrice", settPrice / skuCount);//含税单价
                        if (isGift == 1) {//是赠品
                            colMap.put("isFree", true);
                        } else {
                            colMap.put("isFree", false);
                        }
                        colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                        colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                        colMap.put("FOwnerId", new Document("FNumber", "100"));//货主开发销售测试
                        colMap.put("FStockId", new Document("FNumber", "XQ03"));//仓库售后退货仓
                        colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态

                        colMap.put("FDeliveryDate", createTime);//退货日期
                        colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                        colMap.put("FSalUnitQty", skuCount);//销售数量
                        colMap.put("FSalBaseQty", skuCount);//销售基本数量
                        colMap.put("FPriceBaseQty", skuCount);//计价基本数量
                        //获取税率信息
                        double tax = (double) taxMap.get(goodsNo);
                        colMap.put("FEntryTaxRate", tax);//税率
                        colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                        colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
                        colMap.put("FIsReturnCheck", false);//发货检验
                        colMap.put("FNote ", goodsMemo);//货品备注
                        FEntity.add(colMap);

                    }
                }
            } else {
                String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
                String unitName = VtuzxUtil.getString(doc, "Unit");
                double settPrice = Math.abs(VtuzxUtil.getDouble(doc, "ShareFavourableAfterFee"));//分摊后金额,对应金蝶含税单价
                double skuCount = Math.abs(VtuzxUtil.getDouble(doc, "SellCount"));
                int isGift = VtuzxUtil.getInt(doc, "IsGift");
                String goodsMemo = VtuzxUtil.getString(doc, "GoodsMemo");//货品备注
                //查询单位编码，直接传文字无效
                String cond = String.format("Fname = '%s'", unitName);
                String unit = (String) unitMap.get(unitName);
                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");//产品类型
                colMap.put("FMaterialId", new Document("FNumber", goodsNo));//物料编码
                colMap.put("FUnitID", new Document("FNumber", unit));//物料单位
                colMap.put("FRealQty", skuCount);//实退数量
                colMap.put("FTaxPrice", settPrice / skuCount);//含税单价 = 分摊后金额 / 数量
                if (isGift == 1) {//是赠品
                    colMap.put("isFree", true);
                } else {
                    colMap.put("isFree", false);
                }
                colMap.put("FReturnType", new Document("FNumber", "THLX01_SYS"));//退货类型
                colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
                colMap.put("FOwnerId", new Document("FNumber", "100"));//货主开发销售测试
                colMap.put("FStockId", new Document("FNumber", "XQ03"));//仓库售后退货仓
                colMap.put("FStockstatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态

                colMap.put("FDeliveryDate", createTime);//退货日期
                colMap.put("FSalUnitID", new Document("FNumber", unit));//销售单位
                colMap.put("FSalUnitQty", skuCount);//销售数量
                colMap.put("FSalBaseQty", skuCount);//销售基本数量
                colMap.put("FPriceBaseQty", skuCount);//计价基本数量
                //获取税率信息
                double tax = (double) taxMap.get(goodsNo);
                colMap.put("FEntryTaxRate", tax);//税率
                colMap.put("FIsOverLegalOrg", false);//组织间结算跨法人标识
                colMap.put("FARNOTJOINQTY", skuCount);//未关联应收数量（计价单位
                colMap.put("FIsReturnCheck", false);//发货检验
                colMap.put("FNote ", goodsMemo);//货品备注
                FEntity.add(colMap);
            }
        }

        payModel.put("SubHeadEntity", SubHeadEntity);
        payModel.put("FEntity", FEntity);
        Map<String, Object> payKneeParam = new LinkedHashMap<>();
        payKneeParam.put("NeedUpDateFields", new ArrayList<>());
        payKneeParam.put("NeedReturnFields", new ArrayList<>());
        payKneeParam.put("IsDeleteEntry", true);
        payKneeParam.put("SubSystemId", "");
        payKneeParam.put("IsVerifyBaseDataField", true);
        payKneeParam.put("IsEntryBatchFill", true);
        payKneeParam.put("ValidateFlag", true);
        payKneeParam.put("NumberSearch", true);
        payKneeParam.put("InterationFlags", "");
        payKneeParam.put("Model", payModel);

        historyDoc.append("param", payModel);
        //创建销售退货单
        try {
            List<VtuzxMap> customerList = kingdeeService.save(client, "SAL_RETURNSTOCK", payKneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            kingdeeService.submit(client, "SAL_RETURNSTOCK", "0", number);
            kingdeeService.audit(client, "SAL_RETURNSTOCK", "0", number, "STK_InvCheckResult");
            historyDoc.append("kingdeeNumber", number);
        } catch (Exception e) {
            throw new VtuzxException(e.getMessage());
        }

    }

    /**
     * 判断客户是否是加密的,在金蝶是否存在,不存在的话做新增
     *
     * @param customerCode
     * @return
     */
    private String getCustomer(String customerCode, VtuzxKingdeeCloudClient client, Document storeDoc, String customerName) throws Exception {
        String customerId = "";//传金蝶的客户编号
        //先判断客户是否加密
        if (customerName.contains("加密")) {//说明是加密的
            customerId = "CUST0012";//加密的客户固定
        } else {//没加密先去金蝶查询是否存在，不存在做新增
            //查询客户
            String cond = String.format("FNumber = '%s'", customerCode);
            List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                    "FNumber",//客户编码
                    "FNAME"//客户名称
            ), cond);
            if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                customerId = customerCode;
            } else {//没有的话做新增

//                Map<String, Object> model = new LinkedHashMap<>();
//                model.put("FCUSTID",0);
//                model.put("FCreateOrgId",new Document("FNumber","100"));
//                model.put("FNumber",customerCode);//客户编码
//                model.put("FUseOrgId",new Document("FNumber","100"));//使用组织
//                model.put("FName",customerName);//客户姓名
//                model.put("FCOUNTRY",new Document("FNumber","China"));
////                model.put("FTEL",telephone);
//                model.put("FINVOICETITLE",customerName);//发票抬头
//                model.put("FIsGroup",false);//集团客户
//                model.put("FIsDefPayer",false);//默认付款方
//                model.put("FCustTypeId",new Document("FNumber","KHLB001_SYS"));//客户类别
//                //TODO
//                model.put("FGroup",new Document("FNumber","07"));//客户分组
//                model.put("FTRADINGCURRID",new Document("FNumber","PRE001"));//结算币别
//                model.put("FInvoiceType","1");//发票类型
//                model.put("FTaxType",new Document("FNumber","SFL02_SYS"));//税分类
//                model.put("FPriority","1");//客户优先级
//                model.put("FTaxRate",new Document("FNumber","SL05_SYS"));//默认税率
//                model.put("FISCREDITCHECK",true);//启用信用管理
//                model.put("FIsTrade",true);//是否交易客户
//                model.put("FUncheckExpectQty",false);//不校验可发量
//                Map<String,Object> customerext = new LinkedHashMap<>();//商务信息
//                customerext.put("FEnableSL",false);//启用商联在线
//                customerext.put("FALLOWJOINZHJ",false);//允许对接智慧订货
//                model.put("FT_BD_CUSTOMEREXT",customerext);
//                Map<String,Object> kneeParam = new LinkedHashMap<>();
//                kneeParam.put("NeedUpDateFields", new ArrayList<>());
//                kneeParam.put("NeedReturnFields", new ArrayList<>());
//                kneeParam.put("IsDeleteEntry", true);
//                kneeParam.put("SubSystemId", "");
//                kneeParam.put("IsVerifyBaseDataField", true);
//                kneeParam.put("IsEntryBatchFill", false);
//                kneeParam.put("ValidateFlag", true);
//                kneeParam.put("NumberSearch", true);
//                kneeParam.put("IsAutoAdjustField", false);
//                kneeParam.put("InterationFlags", "");
//                kneeParam.put("IgnoreInterationFlag", "");
//                kneeParam.put("IsControlPrecision", false);
//                kneeParam.put("ValidateRepeatJson", false);
//                kneeParam.put("Model", model);
//                try {
//                    //新增客户
//                    List<VtuzxMap> customerList = kingdeeService.save(client, "BD_Customer",kneeParam);
//                    VtuzxMap kingdeeCustomerMap = customerList.get(0);
//                    String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
//                    kingdeeService.submit(client, "BD_Customer", "0", number);
//                    kingdeeService.audit(client, "BD_Customer", "0", number,"STK_InvCheckResult");
//                    customerId = customerCode;
//                } catch (Exception e) {
//                    _logger.info(e.getMessage());
//                }
            }
        }
        return customerId;
    }

    /**
     * 获取客户编码(客户传销售渠道)
     *
     * @return
     */
    private String getCustomerShopName(VtuzxKingdeeCloudClient client, String shopName) throws Exception {
        String customerId = "";//传金蝶的客户编号

        //查询客户
        String cond = String.format("FName = '%s' and FForbidStatus ='%s' ", shopName, "A");
        List<VtuzxMap> bd_customer = kingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                "FNumber",//客户编码
                "FNAME"//客户名称
        ), cond);
        if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
            customerId = VtuzxUtil.getString(bd_customer.get(0), "FNumber");
        }

        return customerId;
    }

    /**
     * 获取部门名称
     *
     * @param
     * @return
     */
    private String getMainDepartName(String seller, Document storeDoc) throws Exception {
        String sellerName = "";
        if (seller.contains("(")) {
            sellerName = seller.substring(0, seller.indexOf('('));//业务员姓名
        } else {
            sellerName = seller;
        }

        //根据姓名查询业务员所属部门
        VtuzxMap sellerMap = jiKeYunApiService.getSeller(storeDoc,
                new VtuzxMap("realNames", sellerName));//员工姓名

        Map<String, Object> sellResult = VtuzxUtil.getObject(sellerMap, "result");

        String mainDepartName = "";
        List<Map<String, Object>> sellData = VtuzxUtil.getObject(sellResult, "data");
        if (!VtuzxUtil.isEmpty(sellData)) {
            Map<String, Object> sellDoc = sellData.get(0);
            mainDepartName = (String) sellDoc.get("mainDepartName");
        }


        return mainDepartName;

    }

    /**
     * 获取金蝶业务员/销售员id
     *
     * @param seller
     * @param client
     * @return
     */
    private String getSellId(String seller, VtuzxKingdeeCloudClient client) throws Exception {
        String sellerName = "";
        if (seller.contains("(")) {
            sellerName = seller.substring(0, seller.indexOf('('));//业务员姓名
        } else {
            sellerName = seller;
        }

        String salesManId = "";
        //查询业务员id
        //查询发货部门id
        String cond = String.format("FName = '%s'", sellerName);
        List<VtuzxMap> bd_operator = kingdeeService.query(client, "BD_OPERATOR", new VtuzxArrayList<>(
                "FNumber",//=业务员编码
                "FNAME"//业务员名称
        ), cond);
        if (bd_operator != null && bd_operator.size() > 0) {//如果有这个客户的话
            salesManId = (String) bd_operator.get(0).get("FNumber");
        }
        return salesManId;
    }


    /**
     * 获取仓库id
     *
     * @param outReldataName 接收方
     * @return
     */
    private String getStockId(String outReldataName, Document storeDoc) throws Exception {
        String stockId = "";
        if (outReldataName.contains("外埠")) {
            stockId = "YXWB01";
        } else {
            //去仓库接口查询部门和仓库
            VtuzxMap stockMap = new VtuzxMap();
            stockMap.append("pageIndex", 0).append("pageSize", 1).append("name", outReldataName);
            VtuzxMap stock = jiKeYunApiService.getStock(storeDoc, stockMap);
            Map<String, Object> result = VtuzxUtil.getObject(stock, "result");
            Map<String, Object> stockData = VtuzxUtil.getObject(result, "data");
            List<Map<String, Object>> warehouseInfo = VtuzxUtil.getObject(stockData, "warehouseInfo");
            stockId = VtuzxUtil.getString(warehouseInfo.get(0), "warehouseCode");//获取仓库编号

        }
        return stockId;
    }

    //同步开始之前
    private ObjectId startUpload(String name, ObjectId userId, Date startTime) {
        String billNo = IXqcConst.createBillNo(BillType.DDTB);
        Document syncDoc = new Document();
        syncDoc.append("createUserName", name)
                .append("createUserId", userId)
                .append("startTime", startTime)
                .append("billNo", billNo);
        ObjectId objectId = syncDao.insertOne(syncDoc);
        return objectId;
    }

    //同步完成之后
    private void endUpload(String name, ObjectId userId, Date endTime, Date startTime, ObjectId objectId) {
        Document syncDoc = syncDao.findById(objectId);
        String billNo = VtuzxUtil.getString(syncDoc, "billNo");
        //查询出同步了多少单据,成功多少,失败多少
        Criteria cond = new Criteria();
        cond.and("userName").is(name);
        cond.and("updateTime").gte(startTime).lte(endTime);
        Iterator<Document> syncOrderItr = syncOrderDao.findList(cond, null, 0, 0);
        List<Document> syncOrderList = new ArrayList<>();
        int successCount = 0;
        int falseCount = 0;
        while (syncOrderItr.hasNext()) {
            Document syncOrderDoc = syncOrderItr.next();
            syncOrderList.add(syncOrderDoc);
            boolean success = VtuzxUtil.getBoolean(syncOrderDoc, "success");
            if (success) {
                successCount++;
            } else {
                falseCount++;
            }
        }
        //订单同步履历上绑定同步单号
        syncOrderDao.updateManyRedirect(cond, new Document("$set", new Document("syncBillNo", billNo)));
        //添加外层表数据
        syncDoc.append("successCount", successCount)
                .append("falseCount", falseCount)
                .append("sumCount", syncOrderList.size())
                .append("endTime", endTime);
        syncDao.updateById(objectId, syncDoc);

    }

//    @Override
//    public void uploadJikeyunAllocation(ObjectId userId, String name, File file, String orderTime) throws Exception {
//        Date startTime = new Date();
//        ObjectId objectId = startUpload(name, userId, startTime);
//        List<VtuzxExcelSheet> sheets = VtuzxExcel.read(file);
//        VtuzxExcelSheet sheet = sheets.get(0);
//        int rowSize = sheet.rowSize();//多少行
//        //避免单据过多,一次只传50条数据
//        int count =  rowSize / 50;//判断有多少个50条数据
//        int remainder = rowSize % 50;//余数
//
//        for (int size = 0; size < count; size++){
//            List<Map<String,Object>> dataList = new ArrayList<>();//导入的excel信息
//            for (int i = size * 50 ; i < (size * 50) + 50; i++) {
//                String skuBarde = "";
//                String materialNo = "";
//                String materialName = "";
//                String specification = "";
//                String unitName = "";
//                double purCount = 0;//数量
//                String remark = "";
//                int cellSize = sheet.row(i).cellSize();
//                for(int ci = 0; ci < cellSize; ci++) {
//                    if (sheet.row(i).cell(ci).col() == 0) skuBarde = sheet.row(i).cell(ci).strCellValue();
//                    if (sheet.row(i).cell(ci).col() == 1) materialNo = sheet.row(i).cell(ci).strCellValue();
//                    if (sheet.row(i).cell(ci).col() == 2) materialName = sheet.row(i).cell(ci).strCellValue();
//                    if (sheet.row(i).cell(ci).col() == 3) specification = sheet.row(i).cell(ci).strCellValue().replaceAll("\\.0", "");
//                    if (sheet.row(i).cell(ci).col() == 4) unitName = sheet.row(i).cell(ci).strCellValue();
//
//                    if (sheet.row(i).cell(ci).col() == 5) purCount = sheet.row(i).cell(ci).doubleCellValue();
//                    if (sheet.row(i).cell(ci).col() == 7) remark = sheet.row(i).cell(ci).strCellValue();
//                }
//                Map<String,Object> data = new HashMap<>();
//                data.put("skuBarde",skuBarde);
//                data.put("materialNo",materialNo);
//                data.put("materialName",materialName);
//                data.put("specification",specification);
//                data.put("unitName",unitName);
//                data.put("purCount",purCount);
//                data.put("remark",remark);
//                dataList.add(data);
//
//            }
//            //传公司间调拨结算单道金蝶
//            uploadJikeyunAllocationBill(userId,name,dataList,orderTime);
//        }
//        //处理一下余数部分
//        if(remainder > 0){
//            List<Map<String,Object>> dataList = new ArrayList<>();//导入的excel信息
//            for (int i = count * 50 ; i < rowSize; i++) {
//                String skuBarde = "";
//                String materialNo = "";
//                String materialName = "";
//                String specification = "";
//                String unitName = "";
//                double purCount = 0;//数量
//                String remark = "";
//                int cellSize = sheet.row(i).cellSize();
//                for(int ci = 0; ci < cellSize; ci++) {
//                    if (sheet.row(i).cell(ci).col() == 0) skuBarde = sheet.row(i).cell(ci).strCellValue();
//                    if (sheet.row(i).cell(ci).col() == 1) materialNo = sheet.row(i).cell(ci).strCellValue();
//                    if (sheet.row(i).cell(ci).col() == 2) materialName = sheet.row(i).cell(ci).strCellValue();
//                    if (sheet.row(i).cell(ci).col() == 3) specification = sheet.row(i).cell(ci).strCellValue().replaceAll("\\.0", "");
//                    if (sheet.row(i).cell(ci).col() == 4) unitName = sheet.row(i).cell(ci).strCellValue();
//
//                    if (sheet.row(i).cell(ci).col() == 5) purCount = sheet.row(i).cell(ci).doubleCellValue();
//                    if (sheet.row(i).cell(ci).col() == 7) remark = sheet.row(i).cell(ci).strCellValue();
//                }
//                Map<String,Object> data = new HashMap<>();
//                data.put("skuBarde",skuBarde);
//                data.put("materialNo",materialNo);
//                data.put("materialName",materialName);
//                data.put("specification",specification);
//                data.put("unitName",unitName);
//                data.put("purCount",purCount);
//                data.put("remark",remark);
//                dataList.add(data);
//            }
//            //传公司间调拨结算单道金蝶
//            uploadJikeyunAllocationBill(userId,name,dataList,orderTime);
//        }
//
//        Date endTime = new Date();
//        endUpload(name,userId,endTime,startTime,objectId);
//    }

    @Override
    public void downloadJikeyunAllocation(ObjectId userId, String name, File file, String orderTime) throws Exception {
        List<VtuzxExcelSheet> sheets = VtuzxExcel.read(file);
        VtuzxExcelSheet sheet = sheets.get(0);
        int rowSize = sheet.rowSize();//多少行
        //避免单据过多,一次只传50条数据
        int count = rowSize / 50;//判断有多少个50条数据

        List<String> billNoList = new ArrayList<>();
        for (int i = 0; i < rowSize ; i++) {
            String billNo = "";
            int cellSize = sheet.row(i).cellSize();
            for (int ci = 0; ci < cellSize; ci++) {
                if (sheet.row(i).cell(ci).col() == 0) billNo = sheet.row(i).cell(ci).strCellValue();
                if (!billNoList.contains(billNo)) {
                    billNoList.add(billNo);
                }
            }
        }

        String billNoStr = String.join(",",billNoList);
        //同步调拨单到中台,判断调拨单是否生成下游单据，如果已经生成的话无法同步，如果未生成可以修改
        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));
        VtuzxMap customerMap = jiKeYunApiService.allocationList(storeDoc,
                new VtuzxMap("allocateNos",billNoStr));

        Map<String, Object> result = VtuzxUtil.getObject(customerMap, "result");
        Map<String, Object> data = VtuzxUtil.getObject(result, "data");
        List<Map<String, Object>> stockAllocateList = VtuzxUtil.getObject(data, "stockAllocate");
        if (stockAllocateList.size() <= 0) {
            return;
        }
        List<Document> allocationList = new ArrayList<>();
        //中台保存
        for (Map<String, Object> stockAllocate : stockAllocateList) {
            String allocateNo = VtuzxUtil.getString(stockAllocate, "allocateNo"); //调拨单号
            List<Map<String, Object>> stockAllocateDetailViews = VtuzxUtil.getObject(stockAllocate, "stockAllocateDetailViews");//货品明细集合
            List<Map<String,Object>> detaiList = new ArrayList<>();
            for (Map<String, Object> detailView : stockAllocateDetailViews){
                Document detailDoc = new Document();
                detailDoc.append("goodsId",VtuzxUtil.getLong(detailView,"goodsId"))
                        .append("goodsName",VtuzxUtil.getString(detailView,"goodsName"))
                        .append("rowRemark",VtuzxUtil.getString(detailView,"rowRemark"))//明细备注
                        .append("skuCount",VtuzxUtil.getDouble(detailView,"skuCount"))
                        .append("unitName",VtuzxUtil.getString(detailView,"unitName"))
                        .append("skuBarcode",VtuzxUtil.getString(detailView,"skuBarcode"))
                        .append("allocateId",VtuzxUtil.getString(detailView, "allocateId"))
                        .append("allocateNo",VtuzxUtil.getString(stockAllocate, "allocateNo"))
                        .append("goodsNo",VtuzxUtil.getString(detailView, "goodsNo"));
                detaiList.add(detailDoc);

            }
            Document allocationDoc = new Document();//保存极客云调拨单
            allocationDoc.append("allocateNo",VtuzxUtil.getString(stockAllocate, "allocateNo"))
                    .append("allocateId",VtuzxUtil.getString(stockAllocate, "allocateId"))
                    .append("outWarehouseId",VtuzxUtil.getString(stockAllocate, "outWarehouseId"))
                    .append("inWarehouseId",VtuzxUtil.getString(stockAllocate, "inWarehouseId"))
                    .append("outWarehouseName",VtuzxUtil.getString(stockAllocate, "outWarehouseName"))
                    .append("intWarehouseName",VtuzxUtil.getString(stockAllocate, "intWarehouseName"))
                    .append("allocateType",VtuzxUtil.getString(stockAllocate, "allocateType"))
                    .append("allocateTypeName",VtuzxUtil.getString(stockAllocate, "allocateTypeName"))
                    .append("applyUserId",VtuzxUtil.getString(stockAllocate, "applyUserId"))
                    .append("applyUserName",VtuzxUtil.getString(stockAllocate, "applyUserName"))
                    .append("applyDepartId",VtuzxUtil.getString(stockAllocate, "applyDepartId"))
                    .append("applyDepartName",VtuzxUtil.getString(stockAllocate, "applyDepartName"))
                    .append("applyDate",VtuzxUtil.getLong(stockAllocate, "applyDate"))
                    .append("operator",VtuzxUtil.getString(stockAllocate, "operator"))
                    .append("operatorId",VtuzxUtil.getString(stockAllocate, "operatorId"))
                    .append("auditUserId",VtuzxUtil.getString(stockAllocate, "auditUserId"))
                    .append("auditUserName",VtuzxUtil.getString(stockAllocate, "auditUserName"))
                    .append("auditDate",VtuzxUtil.getLong(stockAllocate, "auditDate"))
                    .append("status",VtuzxUtil.getString(stockAllocate, "status"))
                    .append("outStatus",VtuzxUtil.getString(stockAllocate, "outStatus"))
                    .append("inStatus",VtuzxUtil.getString(stockAllocate, "inStatus"))
                    .append("memo",VtuzxUtil.getString(stockAllocate, "memo"))
                    .append("goodsCount",VtuzxUtil.getInt(stockAllocate, "goodsCount"))
                    .append("skuCount",VtuzxUtil.getInt(stockAllocate, "skuCount"))
                    .append("gmtCreate",VtuzxUtil.getLong(stockAllocate, "gmtCreate"))
                    .append("companyName",VtuzxUtil.getString(stockAllocate, "companyName"))
                    .append("stockAllocateDetailViews",detaiList)
                    .append("inCountSum",VtuzxUtil.getInt(stockAllocate, "inCountSum"))
                    .append("outCountSum",VtuzxUtil.getInt(stockAllocate, "outCountSum"))
                    .append("outWarehouseCode",VtuzxUtil.getString(stockAllocate, "outWarehouseCode"))
                    .append("intWarehouseCode",VtuzxUtil.getString(stockAllocate, "intWarehouseCode"))
                    .append("isUpload",false);

            Document jackAllocaeDoc = bainianAllocationDao.findOne(Criteria.where("allocateNo").is(allocateNo));
            if (VtuzxUtil.isEmpty(jackAllocaeDoc)){//如果没添加过
//                bainianAllocationDao.insertOne(allocationDoc);//添加到极客云调拨表
                allocationList.add(allocationDoc);
                _logger.info(String.format("添加吉客云调拨单号%s",allocateNo));
            } else {
                Boolean isUpload = VtuzxUtil.getBoolean(jackAllocaeDoc,"isUpload");
                if (!isUpload){
                    bainianAllocationDao.updateOne(Criteria.where("allocateNo").is(allocateNo),allocationDoc);
                }
            }

        }
        if(!VtuzxUtil.isEmpty(allocationList)){
            bainianAllocationDao.insertMany(allocationList);
        }
    }

    @Override
    public VtuzxMap uploadJikeyunAllocationBill(ObjectId userId, String userName, List<Map<String,Object>> dataList, String type,List<String> allocateNoList) throws Exception {

        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));

        List<Map<String,Object>> stockAllocateDetailViews = new ArrayList<>();//创建调拨单中的货品明细

        for (Map<String,Object> materialMap : dataList){
            Map<String,Object> addMaterial = new HashMap<>();

            Double skuCount = 0.0;
            if (type.equals("wei")){
                skuCount = VtuzxUtil.getDouble(materialMap,"weiUse");//数量
            } else {
                skuCount = VtuzxUtil.getDouble(materialMap,"daUse");//数量
            }
            String outSkuCode = VtuzxUtil.getString(materialMap,"skuBarcode");//条码
            String goodsNo = VtuzxUtil.getString(materialMap,"goodsNo");//物料编码
            String unitName = VtuzxUtil.getString(materialMap,"unitName");//单位
            String goodsName = VtuzxUtil.getString(materialMap,"goodsName");//物料名称
            String allocateNo = VtuzxUtil.getString(materialMap,"allocateNo");//调拨单号

            addMaterial.put("outSkuCode",outSkuCode);
            addMaterial.put("skuCount",skuCount);
            addMaterial.put("unitName",unitName);
            addMaterial.put("isCertified",1);
            addMaterial.put("rowRemark",allocateNo);
            addMaterial.put("isBatch",0);
            addMaterial.put("goodsName",goodsName);
            addMaterial.put("goodsNo",goodsNo);
            addMaterial.put("skuBarcode",goodsNo);
            stockAllocateDetailViews.add(addMaterial);
        }


        VtuzxMap param = new VtuzxMap();
        param.append("outCurrencyCode","CNY")
                .append("allocateType",0)
                .append("companyName","百年晓芹（大连）生态食品有限公司")
                .append("memo","调拨传单")
                .append("departCode","98")
                .append("inCurrencyCode","CNY")
                .append("stockAllocateDetailViews",stockAllocateDetailViews)
                .append("currencyRate",1)
                .append("allocatePriceType","1")
                .append("companyCode","YX01")
                .append("applyUserName","蒋岳霖")
                .append("outCurrencyName","人民币")
                .append("status","0")
                .append("applyUserId",1)
                .append("inCurrencyName","人民币")
                .append("intWarehouseCode","XQBB00066");
        if (type.equals("wei")){
            param.append("outWarehouseCode","XQBB00068");//委外仓
        } else {
            param.append("outWarehouseCode","XQWG00101");//大连总仓
        }

        try {
            VtuzxMap resultMap = jiKeYunApiService.allocatteCreate(storeDoc, param);
            Map<String,Object> result = VtuzxUtil.getObject(resultMap,"result");
            Map<String,Object> data = VtuzxUtil.getObject(result,"data");
            String allocateNo = VtuzxUtil.getString(data,"allocateNo");
            if (type.equals("wei")){
                Criteria cond = Criteria.where("allocateNo").in(allocateNoList);
                bainianAllocationDao.updateMany(cond,new Document("weiAllocateNo",allocateNo));
            } else {
                Criteria cond = Criteria.where("allocateNo").in(allocateNoList);
                bainianAllocationDao.updateMany(cond,new Document("daAllocateNo",allocateNo));
            }
        } catch (Exception e){
            _logger.info(e.getMessage());
            throw new VtuzxException(e.getMessage());
        }
        return null;
    }

    /**
     * 获取待同步列表
     */
    @Override
    public VtuzxMap getSyncListLatest(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        // 构建查询条件
        Criteria cond = new Criteria();
        // 分页查询（按orderTime降序）
        VtuzxPage page = syncTaskDao.page(cond, new Document("orderTime", -1), pageIndex, pageSize);
        // 处理结果集
        List<VtuzxMap> dataList = page.iterator(doc ->
                        new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                                .append("billTaskNo", VtuzxUtil.getString(doc, "billTaskNo"))
                                .append("orderType", VtuzxUtil.getString(doc, "orderType"))
                                .append("orderTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(doc.getDate("orderTime")))
                                .append("errorMsg", VtuzxUtil.getString(doc, "errorMsg")));
        return new VtuzxMap(IVtuzxConst.Key_total, page.total())
                .append(IVtuzxConst.Key_data, dataList);
    }

    /**
     * 获取已同步列表
     */
    @Override
    public VtuzxMap getSyncListHistory(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        // 构建查询条件
        Criteria cond = new Criteria();
        // 分页查询（按orderTime降序）
        VtuzxPage page = syncTaskHistoryDao.page(cond, new Document("syncedTime", -1), pageIndex, pageSize);
        // 处理结果集
        List<VtuzxMap> dataList = page.iterator(doc ->
                        new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                                .append("billTaskNo", VtuzxUtil.getString(doc, "billTaskNo"))
                                .append("orderType", VtuzxUtil.getString(doc, "orderType"))
                                .append("orderTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(doc.getDate("orderTime")))
                                //.append("kingdeeId", VtuzxUtil.getString(doc, "kingdeeId"))
                                .append("syncedTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(doc.getDate("syncedTime")))
                                .append("errorMsg", VtuzxUtil.getString(doc, "errorMsg")));
        return new VtuzxMap(IVtuzxConst.Key_total, page.total())
                .append(IVtuzxConst.Key_data, dataList);
    }

    /**
     * 获取自采品列表
     */
    @Override
    public VtuzxMap getSelfItemList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        // 构建查询条件
        Criteria cond = new Criteria();
        // 分页查询
        VtuzxPage page = selfProductDao.page(cond, null, pageIndex, pageSize);
        // 处理结果集
        List<VtuzxMap> dataList = page.iterator(doc ->
                new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                        .append("selfProductNo", VtuzxUtil.getString(doc, "selfProductNo"))
                        .append("selfProductName", VtuzxUtil.getString(doc, "selfProductName")));
        return new VtuzxMap(IVtuzxConst.Key_total, page.total())
                .append(IVtuzxConst.Key_data, dataList);
    }

    /**
     * 获取吉客云仓库列表
     */
    @Override
    public VtuzxMap getWarehouseList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        // 构建查询条件
        Criteria cond = new Criteria();
        // 分页查询（按warehouseCode升序）
        VtuzxPage page = warehouseDao.page(cond, null, pageIndex, pageSize);
        // 处理结果集
        List<VtuzxMap> dataList = page.iterator(doc ->
                new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                        .append("warehouseCode", VtuzxUtil.getString(doc, "warehouseCode"))
                        .append("warehouseName", VtuzxUtil.getString(doc, "warehouseName"))
                        .append("warehouseTypeName", VtuzxUtil.getString(doc, "warehouseTypeName"))
                        .append("warehouseCompanyName", VtuzxUtil.getString(doc, "warehouseCompanyName"))
                        .append("warehouseDepartName", VtuzxUtil.getString(doc, "warehouseDepartName"))
                        .append("linkMan", VtuzxUtil.getString(doc, "linkMan"))
                        .append("tel", VtuzxUtil.getString(doc, "tel"))
                        .append("address", VtuzxUtil.getString(doc, "address"))
                        .append("memo", VtuzxUtil.getString(doc, "memo")));
        return new VtuzxMap(IVtuzxConst.Key_total, page.total())
                .append(IVtuzxConst.Key_data, dataList);
    }

    /**
     * 根据待同步列表自动同步调拨单
     */
    public VtuzxMap syncListAllocationLatest(Date from, Date to) {
        VtuzxMap syncResult = new VtuzxMap();
        int successCount = 0;
        int failCount = 0;
        List<String> errorMessages = new ArrayList<>();
        List<Document> syncTaskList = new ArrayList<>();
        //查询待同步的调拨单
        Criteria cond = Criteria.where("orderTime").gte(from).lte(to).and("orderType").is("调拨单");
        Iterator<Document> syncTaskIterator = syncTaskDao.findList(cond, null, 0, 0);
        //获得待同步列表集合
        while (syncTaskIterator.hasNext()) {
            syncTaskList.add(syncTaskIterator.next());
        }
        //遍历待同步列表集合
        for (Document syncTaskDoc : syncTaskList) {
            try {
                //单据为调拨单
                String allocationId = VtuzxUtil.getString(syncTaskDoc, "billTaskNo");
                String taskTime = VtuzxUtil.getString(syncTaskDoc, "orderTime");
                syncTaskAllocation(allocationId, taskTime);
                //同步成功后移动到已同步列表
                String collName = "t_sync_task";
                String historyCollName = "t_sync_task_history";
                //根据billTaskNo查找
                Criteria condTask = Criteria.where("billTaskNo").is(allocationId);
                //查询
                Document dateToMove = syncTaskDao.findOne(collName, condTask);
                //插入文档
                Document docForTarget = new Document(dateToMove);
                syncTaskHistoryDao.insertOne(historyCollName, docForTarget, null);
                String _id = VtuzxUtil.getString(dateToMove, "_id");
                syncTaskHistoryDao.updateById(_id, new Document("syncedTime", new Date()));
                syncTaskHistoryDao.updateById(_id, new Document("errorMsg", "-"));
                syncTaskHistoryDao.updateById(_id, new Document("isUpload", "yes"));
                //删除文档
                syncTaskDao.deleteOne(collName, cond, null);
                successCount++;
                syncResult.append("success", true).append("message", "同步成功").append("errors", "");
            } catch(Exception e){
                String allocationId = VtuzxUtil.getString(syncTaskDoc, "billTaskNo");
                failCount++;
                String collName = "t_sync_task";
                Criteria condBill = Criteria.where("billTaskNo").is(allocationId);
                Document dateToFailed = syncTaskDao.findOne(collName, condBill);
                String _id = VtuzxUtil.getString(dateToFailed, "_id");
                syncTaskDao.updateById(_id, new Document("syncedTime", new Date()));
                syncTaskDao.updateById(_id, new Document("errorMsg", e.getMessage()));
                syncResult.append("failed", false).append("message", "同步失败:" + e.getMessage());
                _logger.info("调拨单" + allocationId + "同步失败:" + e.getMessage());
            }
        }
        //补充校验，防止单据已经插入成功并传入历史表但待同步列表中未删除
        checkAndFixInconsistentData();
        //返回统计结果
        return syncResult.append("successCount", successCount).append("failCount", failCount).append("errors", errorMessages);
    }

    /**
     * 调拨单同步方法
     */
    private void syncTaskAllocation(String allocationId, String taskTime) throws Exception {
        //登录金蝶客户端
        VtuzxKingdeeCloudClient clientYX = kingdeeService.loginKingdeeYeXiang();
        //用allocationId直接在JikeyunAllocationDao中查询此条调拨单数据
        //保存调拨单数据为allocation
        Document allocation = jikeyunAllocationDao.findOne(Criteria.where("allocateNo").is(allocationId));
        if (allocation == null) {
            throw new VtuzxException("不存在编号为" + allocationId + "的调拨单");
        }
        // 提取仓库信息
        String source = VtuzxUtil.getString(allocation, "outWarehouseCode");
        String target = VtuzxUtil.getString(allocation, "intWarehouseCode");
        String FCustomerID = VtuzxUtil.getString(allocation, "applyDepartName");
//        ObjectId userId = VtuzxUtil.getObject(allocation, "userId");
//        String userName = VtuzxUtil.getString(allocation, "userName");
        Date syncTime = new Date();
        String gmtCreate = VtuzxUtil.getString(allocation, "gmtCreate");
        List<String> materialNoList = new ArrayList<>();//物料编码集合
        //获取调拨单中的物料集合
        List<Document> goodsList = VtuzxUtil.getObject(allocation, "stockAllocateDetailViews");
        //遍历物料集合
        for (Document goodsMap : goodsList) {
            //添加物料编码集合
            String materialNo = VtuzxUtil.getString(goodsMap, "goodsNo");
            if (!materialNoList.contains(materialNo)) {
                materialNoList.add(materialNo);
            }
        }
        VtuzxMap materialMap = new VtuzxMap();
        //根据物料编码集合查询物料信息
        Iterator<Document> materialItr = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materialItr.hasNext()) {
            Document mtr = materialItr.next();
            VtuzxMap mtrMap = new VtuzxMap();
            String materialNumber = VtuzxUtil.getString(mtr, "fNumber");
            String materialName = VtuzxUtil.getString(mtr, "fName");
            String fSpecification = VtuzxUtil.getString(mtr, "fSpecification");
            String fBaseUnitIdFName = VtuzxUtil.getString(mtr, "fBaseUnitIdFName");
            mtrMap.append("materialName", materialName);
            mtrMap.append("materialSpec", fSpecification);
            mtrMap.append("unit", fBaseUnitIdFName);
            mtrMap.append("materialNo", materialNumber);
            materialMap.append(materialNumber, mtrMap);
        }
        Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
            Document getGoods = (Document) goodsMap.get(goodsNo);
            if (!materialNoList.contains(goodsNo)) {
                materialNoList.add(goodsNo);
            }
            if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                goodsMap.put(goodsNo, doc);
            } else {
                int skuCount = VtuzxUtil.getInt(doc, "skuCount");
                int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                doc.replace("skuCount", skuCount + skuNowCount);
                goodsMap.put(goodsNo, doc);
            }
        }
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");
            priceMap.put(materialNo, currentPrice);
        }
        Document historyDoc = syncOrderDao.findOne(Criteria.where("billNo").is(allocationId));
        ObjectId id = null;
        if (historyDoc == null) {
            historyDoc = new Document("billNo", allocationId);
        } else {
            id = VtuzxUtil.getObject(historyDoc, "_id");
        }
        Document syncTaskDoc = syncTaskDao.findOne(Criteria.where("billTaskNo").is(allocationId));
        historyDoc.append("billNo", allocationId);
        historyDoc.append("source", "JKY");
        historyDoc.append("data", syncTaskDoc);
        historyDoc.append("event", "syncTask");
        historyDoc.append("taskTime", taskTime);
        /*String success = "";//方法返回信息*/
        try {
            if ("XQBB00066".equals(source) && "XQWG00101".equals(target)) {
                //XQBB00066 新工厂总仓  =>  XQWG00101 大连总仓
                //新工厂 销售出
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFOwnerID", "200")
                        .append("flagForFStockID", "001")
                        .append("flagForFSaleOrgId", "200")
                        .append("flagForFCustomerID", "CUST0018")
                        .append("flagForFStockOrgId", "200")
                        .append("flagForFReceiverID", "CUST0018")
                        .append("flagForFSettleID", "CUST0018")
                        .append("flagForFPayerID", "CUST0018")
                        .append("flagForFSaleDeptID", "02")
                        .append("priceMap", priceMap);
                syncKingdeeSaleOutTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID);
            } else if ("XQWG00101".equals(source) && "XQBB00066".equals(target)) {
                //XQWG00101 大连总仓  =>  XQBB00066 新工厂总仓
                //新工厂 采购入
                VtuzxMap FID = new VtuzxMap()
                        .append("flagFStockOrgId", "200")
                        .append("flagFDemandOrgId", "200")
                        .append("flagFPurchaseOrgId", "200")
                        .append("flagFSupplierId", "05.0002")
                        .append("flagFCorrespondOrgId", "200")
                        .append("flagFOwnerIdHead", "200")
                        .append("flagForFStockID", "001");
                syncKingdeeProcureTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID);
            } else if ("XQBB00071".equals(source) && "XQWG00116".equals(target)) {
                //XQBB00071 新工厂电商—物流出库仓库  =>  XQWG00116 电商——物流出库仓库
                //新工厂 销售出
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFOwnerID", "200")
                        .append("flagForFStockID", "001")
                        .append("flagForFSaleOrgId", "200")
                        .append("flagForFCustomerID", "CUST0014")
                        .append("flagForFStockOrgId", "200")
                        .append("flagForFReceiverID", "CUST0014")
                        .append("flagForFSettleID", "CUST0014")
                        .append("flagForFPayerID", "CUST0014")
                        .append("priceMap", priceMap);
                syncKingdeeSaleOutTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID);
            } else if ("XQWG00116".equals(source) && "XQBB00071".equals(target)) {
                //XQWG00116 电商——物流出库仓库  =>  XQBB00071 新工厂电商—物流出库仓库
                //新工厂 采购入
                VtuzxMap FID = new VtuzxMap()
                        .append("flagFStockOrgId", "200")
                        .append("flagFDemandOrgId", "200")
                        .append("flagFPurchaseOrgId", "200")
                        .append("flagFSupplierId", "05.0002")
                        .append("flagFCorrespondOrgId", "200")
                        .append("flagFOwnerIdHead", "200")
                        .append("flagForFStockID", "001");
                syncKingdeeProcureTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID);
            } else if ("XQBBWL01".equals(source) && "XQBB00074".equals(target)) {
                //XQBBWL01 本埠物流仓  =>  XQBB00074	百年晓芹本埠物流仓
                //新工厂 采购入
                VtuzxMap FID = new VtuzxMap()
                        .append("flagFStockOrgId", "200")
                        .append("flagFDemandOrgId", "200")
                        .append("flagFPurchaseOrgId", "200")
                        .append("flagFSupplierId", "05.0002")
                        .append("flagFCorrespondOrgId", "200")
                        .append("flagFOwnerIdHead", "200")
                        .append("flagForFStockID", "001")
                        .append("flagForFOWNERID", "200")
                        .append("priceMap", priceMap);
                syncKingdeeProcureTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID);
            } else if ("XQBB00074".equals(source) && "XQBBWL01".equals(target)) {
                //XQBB00074	百年晓芹本埠物流仓  =>  XQBBWL01 本埠物流仓
                //新工厂 销售出
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFOwnerID", "200")
                        .append("flagForFStockID", "001")
                        .append("flagForFSaleOrgId", "200")
                        .append("flagForFCustomerID", "CUST0018")
                        .append("flagForFStockOrgId", "200")
                        .append("flagForFReceiverID", "CUST0018")
                        .append("flagForFSettleID", "CUST0018")
                        .append("flagForFPayerID", "CUST0018")
                        .append("priceMap", priceMap);
                syncKingdeeSaleOutTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID);
            } else if ("XQBB00074".equals(source) && YEXIANG_WAREHOUSECODE.contains(target)) {
                //XQBB00074 百年晓芹本埠物流仓  =>  门店仓
                //（跨组织）直接调拨单
                //从金蝶查询调入仓库
                String intWarehouseName = VtuzxUtil.getString(allocation, "intWarehouseName");
                String FDestStockId = "";
                if (!VtuzxUtil.isEmpty(intWarehouseName)) {//如果吉客云调入仓库名称不为空，查询金蝶仓库id
                    //查询金蝶仓库id
                    String cond = String.format("FName = '%s'", intWarehouseName);
                    List<VtuzxMap> bd_stock = kingdeeService.query(clientYX, "BD_STOCK", new VtuzxArrayList<>(
                            "FNumber",//仓库编码
                            "FNAME"//仓库
                    ), cond);
                    if (bd_stock != null && bd_stock.size() > 0) {//如果有这个仓库的话
                        //调入仓库
                        FDestStockId = bd_stock.get(0).getString("FNumber");
                    }
                }
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFSrcStockID", "001")
                        .append("flagForFDestStockId", FDestStockId)
                        .append("flagForFSettleOrgId", "200")
                        .append("flagForFSaleOrgId", "200")
                        .append("flagForFStockOutOrgId", "200")
                        .append("flagForFOwnerOutIdHead", "200")
                        .append("flagForFStockOrgId", "100")
                        .append("flagForFOwnerIdHead", "100")
                        .append("flagForFOwnerOutId", "200")
                        .append("flagForFOwnerId", "100")
                        .append("flagForFKeeperId", "100")
                        .append("flagForFKeeperOutId", "200");
                syncKingdeeInnerAllocationTask(clientYX, allocation, goodsList, historyDoc, FID);
            } else if ("YXJDP01".equals(source) && YEXIANG_WAREHOUSECODE.contains(target)) {
                //YXJDP01 鸡蛋票、油、小米粥总仓-野象  =>  门店仓
                //（组织内）直接调拨单
                String FOUTDEPTID = "05";
                String FINDEPTID = "";
                String intWarehouseName = VtuzxUtil.getString(allocation, "intWarehouseName");
                String FINDEPTName = intWarehouseName.substring(0, intWarehouseName.indexOf("-"));
                if (!VtuzxUtil.isEmpty(FINDEPTName)) {//如果吉客云部门名称不为空，查询金蝶部门id
                    //查询收货部门id
                    String cond = String.format("FName = '%s' and FForbidStatus ='%s'", FINDEPTName, "A");
                    List<VtuzxMap> bd_department = kingdeeService.query(clientYX, "BD_Department", new VtuzxArrayList<>(
                            "FNumber",//=部门编码
                            "FNAME"//部门
                    ), cond);
                    if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                        //调入部门
                        FINDEPTID = (String) bd_department.get(0).get("FNumber");
                    }
                }
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFSrcStockID", source)
                        .append("flagForFDestStockId", target)
                        .append("flagForFSettleOrgId", "100")
                        .append("flagForFSaleOrgId", "100")
                        .append("flagForFStockOutOrgId", "100")
                        .append("flagForFOwnerOutIdHead", "100")
                        .append("flagForFStockOrgId", "100")
                        .append("flagForFOwnerIdHead", "100")
                        .append("flagForFOwnerOutId", "100")
                        .append("flagForFOwnerId", "100")
                        .append("flagForFKeeperId", "100")
                        .append("flagForFKeeperOutId", "100")
                        .append("flagForFOUTDEPTID", FOUTDEPTID)
                        .append("flagForFINDEPTID", FINDEPTID)
                        .append("flagForFTransferBizType", "InnerOrgTransfer")
                        .append("priceMap", priceMap);
                syncKingdeeInnerAllocationTask(clientYX, allocation, goodsList, historyDoc, FID);
            } else if (YEXIANG_WAREHOUSECODE.contains(source) && "XQBB00067".equals(target)) {
                //门店仓  =>  XQBB00067 新工厂退货仓
                if (selfProductBillDao.isSelfProductBill(allocationId)) {
                    //处理自采品拆分
                    handleSelfProductSplit(allocation, historyDoc, clientYX);
                } else if (!selfProductBillDao.isSelfProductBill(allocationId)) {
                    //（跨组织）直接调拨单
                    VtuzxMap FID = new VtuzxMap()
                            .append("flagForFSrcStockID", source)
                            .append("flagForFDestStockId", "001")
                            .append("flagForFSettleOrgId", "100")
                            .append("flagForFSaleOrgId", "100")
                            .append("flagForFStockOutOrgId", "100")
                            .append("flagForFOwnerOutIdHead", "100")
                            .append("flagForFStockOrgId", "200")
                            .append("flagForFOwnerIdHead", "200")
                            .append("flagForFOwnerOutId", "100")
                            .append("flagForFOwnerId", "200")
                            .append("flagForFKeeperId", "200")
                            .append("flagForFKeeperOutId", "100");
                    syncKingdeeInnerAllocationTask(clientYX, allocation, goodsList, historyDoc, FID);
                } else {
                    throw new VtuzxException("数据异常");
                }
            } else if (YEXIANG_WAREHOUSECODE.contains(source) && "XQ03".equals(target)) {
                //门店仓  =>  XQ03 大连总售后退货仓
                if (selfProductBillDao.isSelfProductBill(allocationId)) {
                    //处理自采品拆分
                    handleSelfProductSplit(allocation, historyDoc, clientYX);
                } else if (!selfProductBillDao.isSelfProductBill(allocationId)) {
                    //没有自采品的单据,全部传销售公司（跨组织）直接调拨单
                    /*//新工厂 销售退
                    VtuzxMap FID = new VtuzxMap()
                            .append("flagForFSaleOrgId", "200")
                            .append("flagForFRetcustId", "CUST0014")
                            .append("flagForFStockOrgId", "200")
                            .append("flagForFReceiveCustId", "CUST0014")
                            .append("flagForFSettleCustId", "CUST0014")
                            .append("flagForFPayCustId", "CUST0014")
                            .append("flagForFSettleOrgId", "200")
                            .append("flagForFOwnerId", "200")
                            .append("flagForFStockId", "001")
                            .append("flagForFStockID", "001")
                            .append("flagForFOwnerIdHead", "100")
                            .append("flagForFSaledeptid", "02")
                            .append("priceMap", priceMap);
                    syncKingdeeSaleReturnTask(clientYX, allocation, goodsList, historyDoc, FID);*/
                    //销售公司 → 新工厂 （跨组织）直接调拨单
                    VtuzxMap FID = new VtuzxMap()
                            .append("flagForFSrcStockID", source)
                            .append("flagForFDestStockId", "001")
                            .append("flagForFSettleOrgId", "100")
                            .append("flagForFSaleOrgId", "100")
                            .append("flagForFStockOutOrgId", "100")
                            .append("flagForFOwnerOutIdHead", "100")
                            .append("flagForFStockOrgId", "200")
                            .append("flagForFOwnerIdHead", "200")
                            .append("flagForFOwnerOutId", "100")
                            .append("flagForFOwnerId", "200")
                            .append("flagForFKeeperId", "200")
                            .append("flagForFKeeperOutId", "100")
                            .append("priceMap", priceMap);
                    syncKingdeeInnerAllocationTask(clientYX, allocation, goodsList, historyDoc, FID);
                } else {
                    throw new VtuzxException("数据异常");
                }
            } else if ("XQBB00072".equals(source) && "XQBB00067".equals(target)) {
                //XQBB00072	新工厂大连电商售后仓  =>  XQBB00067	新工厂退货仓
                //step1
                //销售公司 销售退
                VtuzxMap FID1 = new VtuzxMap()
                        /*.append("flagFSaleOrgId", "100")
                        .append("flagFRetcustId", FCustomerID)
                        .append("flagFStockOrgId", "100")
                        .append("flagFReceiveCustId", FCustomerID)
                        .append("flagFSettleCustId", FCustomerID)
                        .append("flagFPayCustId", FCustomerID)
                        .append("flagFSettleOrgId", "100")
                        .append("flagFOwnerId", "100")
                        .append("flagFStockId", source);*/
                        .append("flagFSaleOrgId", "100")
                        .append("flagFRetcustId", "03.01.017")
                        .append("flagFStockOrgId", "100")
                        .append("flagFReceiveCustId", "03.01.017")
                        .append("flagFSettleCustId", "03.01.017")
                        .append("flagFPayCustId", "03.01.017")
                        .append("flagFSettleOrgId", "100")
                        .append("flagFOwnerId", "100")
                        .append("flagFStockId", "YXBBTQ01");
                syncKingdeeSaleReturnTask(clientYX, allocation, goodsList, historyDoc, FID1);
                //step2
                //销售公司 采购退
                VtuzxMap FID2 = new VtuzxMap()
                        .append("flagForFStockOrgId", "100")
                        .append("flagForFRequireOrgId", "100")
                        .append("flagForFPurchaseOrgId", "100")
                        .append("flagForFSupplierID", "05.0002")
                        .append("flagForFACCEPTORID", "05.0002")
                        .append("flagForFSettleId", "05.0002")
                        .append("flagForFCHARGEID", "05.0002")
                        .append("flagForFOwnerIdHead", "100")
                        .append("flagForFSettleOrgId", "100")
                        //.append("flagForFStockID", source)
                        .append("flagForFStockID", "YXBBTQ01")
                        .append("flagForFOWNERID", "100");
                syncKingdeeRefundXYTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID2);
                //step3
                //新工厂 销售退
                VtuzxMap FID3 = new VtuzxMap()
                        .append("flagForFSaleOrgId", "200")
                        .append("flagForFRetcustId", "CUST0014")
                        .append("flagForFStockOrgId", "200")
                        .append("flagForFReceiveCustId", "CUST0014")
                        .append("flagForFSettleCustId", "CUST0014")
                        .append("flagForFPayCustId", "CUST0014")
                        .append("flagForFSettleOrgId", "200")
                        .append("flagForFOwnerId", "200")
                        .append("flagForFStockID", "001");
                syncKingdeeSaleReturnTask(clientYX, allocation, goodsList, historyDoc, FID3);
            } else if ("XQBB00067".equals(source) && "XQ03".equals(target)) {
                //XQBB00067 新工厂退货仓  =>  XQ03 大连总售后退货仓
                //新工厂 采购退
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFStockOrgId", "200")
                        .append("flagForFRequireOrgId", "200")
                        .append("flagForFPurchaseOrgId", "200")
                        .append("flagForFSupplierID", "05.0002")
                        .append("flagForFACCEPTORID", "05.0002")
                        .append("flagForFSettleId", "05.0002")
                        .append("flagForFCHARGEID", "05.0002")
                        .append("flagForFOwnerIdHead", "200")
                        .append("flagForFSettleOrgId", "200")
                        .append("flagForGmtCreate", gmtCreate)
                        .append("flagForFStockID", "001")
                        .append("priceMap", priceMap)
                        .append("flagForFOWNERID", "200");
                syncKingdeeRefundXYTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID);
            } else if ("XQ03".equals(source) && "XQBB00067".equals(target)) {
                //XQ03 大连总售后退货仓  =>  XQBB00067 新工厂退货仓
                //新工厂 销售退
                VtuzxMap FID3 = new VtuzxMap()
                        .append("flagForFSaleOrgId", "200")
                        .append("flagForFRetcustId", "CUST0014")
                        .append("flagForFStockOrgId", "200")
                        .append("flagForFReceiveCustId", "CUST0014")
                        .append("flagForFSettleCustId", "CUST0014")
                        .append("flagForFPayCustId", "CUST0014")
                        .append("flagForFSettleOrgId", "200")
                        .append("flagForFOwnerId", "200")
                        .append("flagForFStockID", "001");
                syncKingdeeSaleReturnTask(clientYX, allocation, goodsList, historyDoc, FID3);
            } else if ("YXJDP01".equals(source) && "XQBB00074".equals(target)) {
                //YXJDP01 鸡蛋票、油、小米粥总仓-野象  =>  XQBB00074 百年晓芹本埠物流仓
                //step1
                //销售公司 销售出
                VtuzxMap FID1 = new VtuzxMap()
                        .append("flagForFOwnerID", "100")
                        .append("flagForFStockID", "YXBBTQ01")
                        .append("flagForFSaleOrgId", "100")
                        .append("flagForFCustomerID", "03.01.017")
                        .append("flagForFStockOrgId", "100")
                        .append("flagForFReceiverID", "03.01.017")
                        .append("flagForFSettleID", "03.01.017")
                        .append("flagForFPayerID", "03.01.017")
                        .append("priceMap", priceMap);
                syncKingdeeSaleOutTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID1);
                //step2
                //新工厂 采购入
                VtuzxMap FID2 = new VtuzxMap()
                        .append("flagFStockOrgId", "200")
                        .append("flagFDemandOrgId", "200")
                        .append("flagFPurchaseOrgId", "200")
                        .append("flagFSupplierId", "05.0002")
                        .append("flagFCorrespondOrgId", "200")
                        .append("flagFOwnerIdHead", "200")
                        .append("flagForFStockID", "001");
                syncKingdeeProcureTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID2);
            } else if ("XQBB00074".equals(source) && "YXJDP01".equals(target)) {
                //XQBB00074 百年晓芹本埠物流仓  =>  YXJDP01 鸡蛋票、油、小米粥总仓-野象
                //step1
                //销售公司 销售退
                VtuzxMap FID1 = new VtuzxMap()
                        /*.append("flagFSaleOrgId", "100")
                        .append("flagFRetcustId", FCustomerID)
                        .append("flagFStockOrgId", "100")
                        .append("flagFReceiveCustId", FCustomerID)
                        .append("flagFSettleCustId", FCustomerID)
                        .append("flagFPayCustId", FCustomerID)
                        .append("flagFSettleOrgId", "100")
                        .append("flagFOwnerId", "100")
                        .append("flagFStockId", source);*/
                        .append("flagFSaleOrgId", "100")
                        .append("flagFRetcustId", "03.01.017")
                        .append("flagFStockOrgId", "100")
                        .append("flagFReceiveCustId", "03.01.017")
                        .append("flagFSettleCustId", "03.01.017")
                        .append("flagFPayCustId", "03.01.017")
                        .append("flagFSettleOrgId", "100")
                        .append("flagFOwnerId", "100")
                        .append("flagFStockId", "YXBBTQ01");
                syncKingdeeSaleReturnTask(clientYX, allocation, goodsList, historyDoc, FID1);
                //step2
                //新工厂 采购退
                VtuzxMap FID2 = new VtuzxMap()
                        .append("flagForFStockOrgId", "200")
                        .append("flagForFRequireOrgId", "200")
                        .append("flagForFPurchaseOrgId", "200")
                        .append("flagForFSupplierID", "05.0002")
                        .append("flagForFACCEPTORID", "05.0002")
                        .append("flagForFSettleId", "05.0002")
                        .append("flagForFCHARGEID", "05.0002")
                        .append("flagForFOwnerIdHead", "200")
                        .append("flagForFSettleOrgId", "200")
                        .append("flagForFStockID", "001")
                        .append("flagForFOWNERID", "200");
                syncKingdeeRefundXYTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID2);
            } else if ("YXJDP01".equals(source) && "XQKFB003".equals(target)) {
                //YXJDP01 鸡蛋票、油、小米粥总仓-野象  => XQKFB003 客服物流备货仓
                //销售公司 销售出
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFOwnerID", "100")
                        .append("flagForFStockID", source)
                        .append("flagForFSaleOrgId", "100")
                        .append("flagForFCustomerID", "CUST0005")
                        .append("flagForFStockOrgId", "100")
                        .append("flagForFReceiverID", "CUST0005")
                        .append("flagForFSettleID", "CUST0005")
                        .append("flagForFPayerID", "CUST0005")
                        .append("priceMap", priceMap);
                syncKingdeeSaleOutTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID);
            } else if ("XQKFB003".equals(source) && "YXJDP01".equals(target)) {
                //XQKFB003 客服物流备货仓  =>  YXJDP01 鸡蛋票、油、小米粥总仓-野象
                //销售公司 销售退
                VtuzxMap FID = new VtuzxMap()
                        /*.append("flagFSaleOrgId", "100")
                        .append("flagFRetcustId", FCustomerID)
                        .append("flagFStockOrgId", "100")
                        .append("flagFReceiveCustId", FCustomerID)
                        .append("flagFSettleCustId", FCustomerID)
                        .append("flagFPayCustId", FCustomerID)
                        .append("flagFSettleOrgId", "100")
                        .append("flagFOwnerId", "100")
                        .append("flagFStockId", source);*/
                        .append("flagFSaleOrgId", "100")
                        .append("flagFRetcustId", "03.01.017")
                        .append("flagFStockOrgId", "100")
                        .append("flagFReceiveCustId", "03.01.017")
                        .append("flagFSettleCustId", "03.01.017")
                        .append("flagFPayCustId", "03.01.017")
                        .append("flagFSettleOrgId", "100")
                        .append("flagFOwnerId", "100")
                        .append("flagFStockId", "YXBBTQ01");
                syncKingdeeSaleReturnTask(clientYX, allocation, goodsList, historyDoc, FID);
            } else if (CHANNEL_WAREHOUSECODE.contains(source) && "XQWG00101".equals(target)) {
                //渠道仓  =>  大连总仓 XQWG00101
                //新工厂	销售出
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFOwnerID", "200")
                        .append("flagForFStockID", "001")
                        .append("flagForFSaleOrgId", "200")
                        .append("flagForFCustomerID", "CUST0018")
                        .append("flagForFStockOrgId", "200")
                        .append("flagForFReceiverID", "CUST0018")
                        .append("flagForFSettleID", "CUST0018")
                        .append("flagForFPayerID", "CUST0018")
                        .append("priceMap", priceMap);
                syncKingdeeSaleOutTask(clientYX, allocation, materialMap, goodsList, historyDoc, FID);
            } else if (CHANNEL_WAREHOUSECODE.contains(source) && YEXIANG_WAREHOUSECODE.contains(target)) {
                //渠道仓  =>  门店仓
                //（跨组织）直接调拨单
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFSrcStockID", "001")
                        .append("flagForFDestStockId", target)
                        .append("flagForFSettleOrgId", "200")
                        .append("flagForFSaleOrgId", "200")
                        .append("flagForFStockOutOrgId", "200")
                        .append("flagForFOwnerOutIdHead", "200")
                        .append("flagForFStockOrgId", "100")
                        .append("flagForFOwnerIdHead", "100")
                        .append("flagForFOwnerOutId", "200")
                        .append("flagForFOwnerId", "100")
                        .append("flagForFKeeperId", "100")
                        .append("flagForFKeeperOutId", "200");
                syncKingdeeInnerAllocationTask(clientYX, allocation, goodsList, historyDoc, FID);
            } else if (CHANNEL_WAREHOUSECODE.contains(source) && "YXJDP01".equals(target)) {
                //渠道仓  =>  YXJDP01 鸡蛋票、油、小米粥总仓-野象
                //（跨组织）直接调拨单
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFSrcStockID", "001")
                        .append("flagForFDestStockId", target)
                        .append("flagForFSettleOrgId", "200")
                        .append("flagForFSaleOrgId", "200")
                        .append("flagForFStockOutOrgId", "200")
                        .append("flagForFOwnerOutIdHead", "200")
                        .append("flagForFStockOrgId", "100")
                        .append("flagForFOwnerIdHead", "100")
                        .append("flagForFOwnerOutId", "200")
                        .append("flagForFOwnerId", "100")
                        .append("flagForFKeeperId", "100")
                        .append("flagForFKeeperOutId", "200");
                syncKingdeeInnerAllocationTask(clientYX, allocation, goodsList, historyDoc, FID);
            } else if (YEXIANG_WAREHOUSECODE.contains(source) && YEXIANG_WAREHOUSECODE.contains(target)) {
                //门店仓  =>  门店仓
                //（组织内）直接调拨单
                String FOUTDEPTID = "";
                String FINDEPTID = "";
                String outWarehouseName = VtuzxUtil.getString(allocation, "outWarehouseName");
                String FINDEPTNameOut = outWarehouseName.substring(0, outWarehouseName.indexOf("-"));
                String intWarehouseName = VtuzxUtil.getString(allocation, "intWarehouseName");
                String FINDEPTNameIn = intWarehouseName.substring(0, intWarehouseName.indexOf("-"));
                //出库门店仓
                if (!VtuzxUtil.isEmpty(FINDEPTNameOut)) {//如果吉客云部门名称不为空，查询金蝶部门id
                    //查询出货部门id
                    String cond = String.format("FName = '%s' and FForbidStatus ='%s'", FINDEPTNameOut, "A");
                    List<VtuzxMap> bd_department = kingdeeService.query(clientYX, "BD_Department", new VtuzxArrayList<>(
                            "FNumber",//=部门编码
                            "FNAME"//部门
                    ), cond);
                    if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                        //调出部门
                        FOUTDEPTID = (String) bd_department.get(0).get("FNumber");
                    }
                }
                //入库门店仓
                if (!VtuzxUtil.isEmpty(FINDEPTNameIn)) {//如果吉客云部门名称不为空，查询金蝶部门id
                    //查询收货部门id
                    String cond = String.format("FName = '%s' and FForbidStatus ='%s'", FINDEPTNameIn, "A");
                    List<VtuzxMap> bd_department = kingdeeService.query(clientYX, "BD_Department", new VtuzxArrayList<>(
                            "FNumber",//=部门编码
                            "FNAME"//部门
                    ), cond);
                    if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                        //调入部门
                        FINDEPTID = (String) bd_department.get(0).get("FNumber");
                    }
                }
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFSrcStockID", source)
                        .append("flagForFDestStockId", target)
                        .append("flagForFSettleOrgId", "100")
                        .append("flagForFSaleOrgId", "100")
                        .append("flagForFStockOutOrgId", "100")
                        .append("flagForFOwnerOutIdHead", "100")
                        .append("flagForFStockOrgId", "100")
                        .append("flagForFOwnerIdHead", "100")
                        .append("flagForFOwnerOutId", "100")
                        .append("flagForFOwnerId", "100")
                        .append("flagForFKeeperId", "100")
                        .append("flagForFKeeperOutId", "100")
                        .append("flagForFOUTDEPTID", FOUTDEPTID)
                        .append("flagForFINDEPTID", FINDEPTID)
                        .append("flagForFTransferBizType", "InnerOrgTransfer")
                        .append("priceMap", priceMap);
                syncKingdeeInnerAllocationTask(clientYX, allocation, goodsList, historyDoc, FID);
            }
            else {
                throw new VtuzxException("无匹配规则: " + source + "->" + target);
            }
            /*//如果方法有返回值,说明有问题
            if (!VtuzxUtil.isEmpty(success)) {
                historyDoc.append("success", false)
                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("_id");
                    historyDoc.append("updateUserId", userId);
                    historyDoc.append("updateUserName", userName);
                    syncOrderDao.updateById(id, historyDoc);
                }
                String _id = VtuzxUtil.getString(allocation, "_id");
                syncTaskDao.updateById(_id, new Document("isUpload", "no"));
            } else {
                historyDoc.append("success", true);
                if (id == null) {
                    syncOrderDao.insertOne(historyDoc);
                } else {
                    historyDoc.remove("id");
                    historyDoc.remove("createTime");
                    historyDoc.remove("updateTime");
                    //不知道为啥remove删除字段后还有信息
                    historyDoc.append("message", "");
                    historyDoc.append("updateUserId", userId);
                    historyDoc.append("updateUserName", userName);
                    syncOrderDao.updateById(id, historyDoc);
                }
                String _id = VtuzxUtil.getString(allocation, "_id");
                syncTaskDao.updateById(_id, new Document("isUpload", "yes"));
                syncTaskDao.updateById(_id, new Document("syncTime", syncTime));
            }*/
            historyDoc.append("success", true);
            if (id == null) {
                syncOrderDao.insertOne(historyDoc);
            } else {
                historyDoc.remove("_id");
                historyDoc.remove("createTime");
                historyDoc.remove("updateTime");
                historyDoc.remove("message");
                syncOrderDao.updateById(id, historyDoc);
            }
        } catch (Exception e) {
            /*if (id == null) {
                syncOrderDao.insertOne(historyDoc);
            } else {
                historyDoc.remove("_id");
                historyDoc.remove("createTime");
                historyDoc.remove("updateTime");
                syncOrderDao.updateById(id, historyDoc);
            }
            _logger.info(e.getMessage());*/
            historyDoc.append("syncTaskAllocation", false).append("message", e.getMessage()).append("success", false);
            if (id == null) {
                syncOrderDao.insertOne(historyDoc);
            } else {
                historyDoc.remove("_id");
                historyDoc.remove("createTime");
                historyDoc.remove("updateTime");
                syncOrderDao.updateById(id, historyDoc);
            }
            throw e;
        }
    }

    /**
     * 根据待同步列表自动同步销售单
     */
    @Override
    public VtuzxMap syncListSaleLatest(Date from, Date to) {
        VtuzxMap syncResult = new VtuzxMap();
        int successCount = 0;
        int failCount = 0;
        List<String> errorMessages = new ArrayList<>();
        List<Document> syncTaskList = new ArrayList<>();
        //查询待同步的销售单
        Criteria cond = Criteria.where("orderTime").gte(from).lte(to).and("orderType").is("销售单");
        Iterator<Document> syncTaskIterator = syncTaskDao.findList(cond, null, 0, 0);
        //获得待同步列表集合
        while (syncTaskIterator.hasNext()) {
            syncTaskList.add(syncTaskIterator.next());
        }
        //遍历待同步列表集合
        for (Document syncTaskDoc : syncTaskList) {
            try {
                //单据为销售单
                String tradeNo = VtuzxUtil.getString(syncTaskDoc, "billTaskNo");
                String taskTime = VtuzxUtil.getString(syncTaskDoc, "orderTime");
                syncTaskSale(tradeNo, taskTime);
//                _logger.info("同步结果 for ID " + tradeNo + ": " + syncResult.get("message"));
                //同步成功后移动到已同步列表
                String collName = "t_sync_task";
                String historyCollName = "t_sync_task_history";
                //根据billTaskNo查找
                Criteria condTask = Criteria.where("billTaskNo").is(tradeNo);
                //查询
                Document dateToMove = syncTaskDao.findOne(collName, condTask);
                //插入文档
                Document docForTarget = new Document(dateToMove);
                syncTaskHistoryDao.insertOne(historyCollName, docForTarget, null);
                String _id = VtuzxUtil.getString(dateToMove, "_id");
                syncTaskHistoryDao.updateById(_id, new Document("syncedTime", new Date()));
                syncTaskHistoryDao.updateById(_id, new Document("errorMsg", "-"));
                syncTaskHistoryDao.updateById(_id, new Document("isUpload", "yes"));
                //删除文档
                syncTaskDao.deleteOne(collName, cond, null);
                successCount++;
                syncResult.append("success", true).append("message", "同步成功").append("errors", "");
                _logger.info("销售单" + tradeNo + "同步成功");
            } catch(Exception e){
                String tradeNo = VtuzxUtil.getString(syncTaskDoc, "billTaskNo");
                failCount++;
                String collName = "t_sync_task";
                Criteria condBill = Criteria.where("billTaskNo").is(tradeNo);
                Document dateToFailed = syncTaskDao.findOne(collName, condBill);
                String _id = VtuzxUtil.getString(dateToFailed, "_id");
                syncTaskDao.updateById(_id, new Document("syncedTime", new Date()));
                syncTaskDao.updateById(_id, new Document("errorMsg", e.getMessage()));
                syncResult.append("failed", false).append("message", "同步失败:" + e.getMessage());
                _logger.info("销售单" + tradeNo + "同步失败:" + e.getMessage());
            }
        }
        //返回统计结果
        return syncResult.append("successCount", successCount).append("failCount", failCount).append("errors", errorMessages);
    }

    /**
     * 销售单同步方法
     */
    private void syncTaskSale(String tradeNo, String taskTime) throws Exception {
        //登录金蝶客户端
        VtuzxKingdeeCloudClient clientYX = kingdeeService.loginKingdeeYeXiang();
        //用tradeNo直接在JikeyunSaleDao中查询此条销售单数据
        //保存调拨单数据为sale
        Document sale = jikeyunSaleDao.findOne(Criteria.where("tradeNo").is(tradeNo));
        if (sale == null) {
            throw new VtuzxException("不存在编号为" + tradeNo + "的销售单");
        }
        List<String> materialNoList = new ArrayList<>();//物料编码集合
        //获取销售单中的物料集合
        List<Document> goodsList = VtuzxUtil.getObject(sale, "goodsDetail");
        //遍历物料集合
        for (Document goodsMap : goodsList) {
            //添加物料编码集合
            String materialNo = VtuzxUtil.getString(goodsMap, "GoodsNo");
            if (!materialNoList.contains(materialNo)) {
                materialNoList.add(materialNo);
            }
        }
        VtuzxMap materialMap = new VtuzxMap();
        //根据物料编码集合查询物料信息
        Iterator<Document> materialItr = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materialItr.hasNext()) {
            Document mtr = materialItr.next();
            VtuzxMap mtrMap = new VtuzxMap();
            String materialNumber = VtuzxUtil.getString(mtr, "fNumber");
            String materialName = VtuzxUtil.getString(mtr, "fName");
            String fSpecification = VtuzxUtil.getString(mtr, "fSpecification");
            String fBaseUnitIdFName = VtuzxUtil.getString(mtr, "fBaseUnitIdFName");
            mtrMap.append("materialName", materialName);
            mtrMap.append("materialSpec", fSpecification);
            mtrMap.append("unit", fBaseUnitIdFName);
            mtrMap.append("materialNo", materialNumber);
            materialMap.append(materialNumber, mtrMap);
        }
        Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
        for (Map<String, Object> goods : goodsList) {
            Document doc = new Document(goods);
            String goodsNo = VtuzxUtil.getString(doc, "GoodsNo");
            Document getGoods = (Document) goodsMap.get(goodsNo);
            if (!materialNoList.contains(goodsNo)) {
                materialNoList.add(goodsNo);
            }
            if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                goodsMap.put(goodsNo, doc);
            } else {
                int skuCount = VtuzxUtil.getInt(doc, "skuCount");
                int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                doc.replace("skuCount", skuCount + skuNowCount);
                goodsMap.put(goodsNo, doc);
            }
        }
        Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
        Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
        //查询物料表获取税率信息
        Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
        while (materials.hasNext()) {
            Document materialDoc = materials.next();
            String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
            String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
            String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
            String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
            String substring = "";
            if (fTaxRateName.startsWith("零")) {
                substring = "0";
            } else {
                substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
            }
            taxMap.put(materialNo, Double.parseDouble(substring));
            unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
        }
        //查询价目表获取价格信息
        Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
        Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
        while (priceItr.hasNext()) {
            Document priceDoc = priceItr.next();
            String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
            Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");
            priceMap.put(materialNo, currentPrice);
        }
        //参数
        double tradeCount = VtuzxUtil.getDouble(sale, "tradeCount");
        String warehouseCode = VtuzxUtil.getString(sale, "warehouseCode");
        String warehouseName = VtuzxUtil.getString(sale, "warehouseName");
//        ObjectId userId = VtuzxUtil.getObject(sale, "userId");
//        String userName = VtuzxUtil.getString(sale, "userName");
        String warehouseCompany = channelDao.getCompanyByWarehouseCode(warehouseCode);
/*        List<String> materialNoList = new ArrayList<>();//物料编码集合
        List<Document> goodsList = VtuzxUtil.getObject(sale, "goodsDetail");
        for (Document goodsMap : goodsList) {
            String materialNo = VtuzxUtil.getString(goodsMap, "goodsNo");
            if (!materialNoList.contains(materialNo)) {
                materialNoList.add(materialNo);
            }
        }*/
        while (materialItr.hasNext()) {
            Document mtr = materialItr.next();
            VtuzxMap mtrMap = new VtuzxMap();
            String materialNumber = VtuzxUtil.getString(mtr, "fNumber");
            String materialName = VtuzxUtil.getString(mtr, "fName");
            String fSpecification = VtuzxUtil.getString(mtr, "fSpecification");
            String fBaseUnitIdFName = VtuzxUtil.getString(mtr, "fBaseUnitIdFName");
            mtrMap.append("materialName", materialName);
            mtrMap.append("materialSpec", fSpecification);
            mtrMap.append("unit", fBaseUnitIdFName);
            mtrMap.append("materialNo", materialNumber);
            materialMap.append(materialNumber, mtrMap);
        }
        Document historyDoc = syncOrderDao.findOne(Criteria.where("billNo").is(tradeNo));
        ObjectId id = null;
        if (historyDoc == null) {
            historyDoc = new Document("billNo", tradeNo);
        } else {
            id = VtuzxUtil.getObject(historyDoc, "_id");
        }
        Document syncTaskDoc = syncTaskDao.findOne(Criteria.where("billTaskNo").is(tradeNo));
        historyDoc.append("billNo", tradeNo);
        historyDoc.append("source", "JKY");
        historyDoc.append("data", syncTaskDoc);
        historyDoc.append("event", "syncTask");
        historyDoc.append("taskTime", taskTime);
        /*String success = "";//方法返回信息*/
        String source = VtuzxUtil.getString(sale, "warehouseCode");
        //获取渠道名称
        String shopName = VtuzxUtil.getString(sale, "shopName");
        //根据渠道名称获取公司名称
        String company = channelDao.getCompanyByName(shopName);
        //根据渠道名称获取渠道分组
        String channelGroup = channelDao.getChannelGroupByName(shopName);
        //根据仓库名称获取公司名称(新工厂/老工厂)
        String warehouseCompanyName = warehouseDao.getCompanyByName(warehouseName);
        //客户名称
        String customerName = VtuzxUtil.getString(sale, "customerName");
        if ("大连晓芹食品有限公司".equals(company)) {
            _logger.info("销售渠道属于大连晓芹食品有限公司的销售单不进行同步");
        } else {
            if (selfProductBillDao.isSelfProductBill(tradeNo)) {
                //处理自采品拆分
                handleSelfProductSplit(sale, historyDoc, clientYX);
            } else {
                try {
                    if ("百年晓芹（大连）生态食品有限公司".equals(company) && "大连晓芹食品有限公司".equals(warehouseCompanyName)) {
                        //渠道是销售公司 发货仓是老工厂
                        //新工厂 采购入
                        VtuzxMap FID = new VtuzxMap()
                                .append("flagFStockOrgId", "200")
                                .append("flagFDemandOrgId", "200")
                                .append("flagFPurchaseOrgId", "200")
                                .append("flagFSupplierId", "05.0002")
                                .append("flagFCorrespondOrgId", "200")
                                .append("flagFOwnerIdHead", "200")
                                .append("flagForFStockID", "001")
                                .append("flagForFOWNERID", "200")
                                .append("priceMap", priceMap)
                                .append("taxMap", taxMap);
                        syncKingdeeProcureTask(clientYX, sale, materialMap, goodsList, historyDoc, FID);
                    }
                    if (tradeCount > 0) {
                        if (CHANNEL_WAREHOUSECODE.contains(warehouseCode) || warehouseCode.equals("XQWG00116")) {
                            //跨组织销售出库单 销售组织:100 发货组织及货主:200
                            String fSaledeptid = "";
                            String FCustomerID = "";
                            String billChannel = "";
                            String cusCode = "";
                            //根据吉客云销售渠道查询金蝶客户名称
                            /*String customerCode = jikeyunChannelCustomerDao.getCodeByChannel(shopName);*/
                            String cusName = jikeyunChannelCustomerDao.getNameByChannel(shopName);
                            //根据金蝶客户名称查询金蝶客户编码
                            String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", cusName, "A");
                            List<VtuzxMap> bd_customer = kingdeeService.query(clientYX, "BD_Customer", new VtuzxArrayList<>(
                                    "FNumber",//客户编码
                                    "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                                    "FNAME"//客户名称
                            ), cusCond);
                            if (bd_customer != null && !bd_customer.isEmpty()) {//如果有这个客户的话
                                //金蝶客户编码
                                cusCode = VtuzxUtil.getString(bd_customer.get(0), "FNumber");
                            }
                            if (channelGroup.equals("网购组") && !shopName.equals("杭州光年有限公司")) {
                                fSaledeptid = "07.02";
                                FCustomerID = cusCode;
                                billChannel = "01";
                            } else if (channelGroup.equals("客服部")) {
                                fSaledeptid = "08";
                                FCustomerID = "06.01.002";
                                billChannel = "07";
                            } else if (shopName.equals("杭州光年有限公司")) {
                                fSaledeptid = "18";
                                FCustomerID = cusCode;
                                billChannel = "09";
                            } else if (channelGroup.equals("财务部")) {
                                fSaledeptid = "16";
                                FCustomerID = "05.01.007";
                                billChannel = "99";
                            }
                            VtuzxMap FID = new VtuzxMap()
                                    .append("flagForFOwnerID", "200")
                                    .append("flagForFRetcustId", "200")
                                    .append("flagForFStockID", "001")
                                    //销售组织FSaleOrgId:100
                                    .append("flagForFSaleOrgId", "100")
                                    .append("flagForFCustomerID", FCustomerID)
                                    //发货组织FStockOrgId:200
                                    .append("flagForFStockOrgId", "200")
                                    .append("flagForFReceiverID", FCustomerID)
                                    .append("flagForFSettleID", FCustomerID)
                                    .append("flagForFPayerID", FCustomerID)
                                    //货主FOwnerIdHead:200
                                    .append("flagForFOwnerIdHead", "200")
                                    .append("flagForFSaledeptid", fSaledeptid)
                                    .append("flagForBillChannel", billChannel)
                                    .append("priceMap", priceMap)
                                    .append("taxMap", taxMap);
                            syncKingdeeSaleOutTask(clientYX, sale, materialMap, goodsList, historyDoc, FID);
                        } else if (YEXIANG_WAREHOUSECODE.contains(warehouseCode)) {
                            //销售公司 销售出
                            String subShopName = shopName.substring(0, shopName.indexOf("-"));
                            String FCustomerID = "";
                            String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", subShopName, "A");
                            List<VtuzxMap> bd_customer = kingdeeService.query(clientYX, "BD_Customer", new VtuzxArrayList<>(
                                    "FNumber",//客户编码
                                    "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                                    "FNAME"//客户名称
                            ), cusCond);
                            if (bd_customer != null && !bd_customer.isEmpty()) {//如果有这个客户的话
                                FCustomerID = VtuzxUtil.getString(bd_customer.get(0), "FNumber");
                            }
                            VtuzxMap FID = new VtuzxMap()
                                    .append("flagForFOwnerID", "100")
                                    .append("flagForFStockID", source)
                                    .append("flagForFSaleOrgId", "100")
                                    .append("flagForFCustomerID", FCustomerID)
                                    .append("flagForFStockOrgId", "100")
                                    .append("flagForFReceiverID", FCustomerID)
                                    .append("flagForFSettleID", FCustomerID)
                                    .append("flagForFPayerID", FCustomerID)
                                    .append("flagForFSaledeptid", "05")
                                    .append("priceMap", priceMap)
                                    .append("taxMap", taxMap);
                            syncKingdeeSaleOutTask(clientYX, sale, materialMap, goodsList, historyDoc, FID);
                        } else if (shopName.startsWith("外埠")) {
                            String FCustomerID = "";
                            String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", customerName, "A");
                            List<VtuzxMap> bd_customer = kingdeeService.query(clientYX, "BD_Customer", new VtuzxArrayList<>(
                                    "FNumber",//客户编码
                                    "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                                    "FNAME"//客户名称
                            ), cusCond);
                            if (bd_customer != null && !bd_customer.isEmpty()) {//如果有这个客户的话
                                FCustomerID = VtuzxUtil.getString(bd_customer.get(0), "FNumber");
                            }
                            VtuzxMap FID = new VtuzxMap()
                                    .append("flagForFOwnerID", "100")
                                    .append("flagForFStockID", source)
                                    .append("flagForFSaleOrgId", "100")
                                    .append("flagForFCustomerID", FCustomerID)
                                    .append("flagForFStockOrgId", "100")
                                    .append("flagForFReceiverID", "CUST0005")
                                    .append("flagForFSettleID", "CUST0005")
                                    .append("flagForFPayerID", "CUST0005")
                                    .append("priceMap", priceMap)
                                    .append("taxMap", taxMap);
                            syncKingdeeSaleOutTask(clientYX, sale, materialMap, goodsList, historyDoc, FID);
                        } else {
                            _logger.info("不符合条件，不进行同步");
                        }
                    } else if (tradeCount < 0) {
                        if (CHANNEL_WAREHOUSECODE.contains(warehouseCode)
                                || (warehouseCode.equals("XQ03") && !shopName.equals("杭州光年有限公司"))
                                || warehouseCode.equals("XQBB00067")) {
                            //跨组织销售退货单 销售组织:100 库存组织及货主:200
                            String fSaledeptid = "";
                            String FCustomerID = "";
                            String billChannel = "";
                            String cusCode = "";
                            //根据吉客云销售渠道查询金蝶客户名称
                            /*String customerCode = jikeyunChannelCustomerDao.getCodeByChannel(shopName);*/
                            String cusName = jikeyunChannelCustomerDao.getNameByChannel(shopName);
                            //根据金蝶客户名称查询金蝶客户编码
                            String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", cusName, "A");
                            List<VtuzxMap> bd_customer = kingdeeService.query(clientYX, "BD_Customer", new VtuzxArrayList<>(
                                    "FNumber",//客户编码
                                    "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                                    "FNAME"//客户名称
                            ), cusCond);
                            if (bd_customer != null && !bd_customer.isEmpty()) {//如果有这个客户的话
                                //金蝶客户编码
                                cusCode = VtuzxUtil.getString(bd_customer.get(0), "FNumber");
                            }
                            if (channelGroup.equals("网购组") && !shopName.equals("杭州光年有限公司")) {
                                fSaledeptid = "07";
                                FCustomerID = cusCode;
                                billChannel = "01";
                            } else if (channelGroup.equals("客服部")) {
                                fSaledeptid = "08";
                                FCustomerID = "06.01.002";
                                billChannel = "07";
                            } else if (shopName.equals("杭州光年有限公司")) {
                                fSaledeptid = "18";
                                FCustomerID = cusCode;
                                billChannel = "09";
                            } else if (channelGroup.equals("财务部")) {
                                fSaledeptid = "16";
                                FCustomerID = "05.01.007";
                                billChannel = "99";
                            }
                            VtuzxMap FID = new VtuzxMap()
                                    .append("flagForFOwnerID", "200")
                                    .append("flagForFOwnerId", "200")
                                    .append("flagForFOWNERID", "200")
                                    .append("flagForFRetcustId", FCustomerID)
                                    .append("flagForFReceiveCustId", "200")
                                    .append("flagForFStockID", "001")
                                    //销售组织FSaleOrgId:100
                                    .append("flagForFSaleOrgId", "100")
                                    .append("flagForFCustomerID", FCustomerID)
                                    //库存组织FStockOrgId:200
                                    .append("flagForFStockOrgId", "200")
                                    .append("flagForFReceiverID", FCustomerID)
                                    .append("flagForFSettleID", FCustomerID)
                                    .append("flagForFSettleOrgId", "100")
                                    .append("flagForFSettleCustId", FCustomerID)
                                    .append("flagForFPayCustId", FCustomerID)
                                    .append("flagForFPayerID", FCustomerID)
                                    //货主FOwnerIdHead:200
                                    .append("flagForFOwnerIdHead", "200")
                                    .append("flagForFSaledeptid", fSaledeptid)
                                    .append("flagForBillChannel", billChannel)
                                    .append("priceMap", priceMap)
                                    .append("taxMap", taxMap);
                            syncKingdeeSaleReturnTask(clientYX, sale, goodsList, historyDoc, FID);
                        } else if (YEXIANG_WAREHOUSECODE.contains(warehouseCode)) {
                            //销售公司 销售退
                            String subShopName = shopName.substring(0, shopName.indexOf("-"));
                            String FCustomerID = "";
                            String cusCond = String.format("FName = '%s' and FForbidStatus ='%s'", subShopName, "A");
                            List<VtuzxMap> bd_customer = kingdeeService.query(clientYX, "BD_Customer", new VtuzxArrayList<>(
                                    "FNumber",//客户编码
                                    "F_SXLJ_xsqd.FNUMBER",//渠道编码(辅助资料)
                                    "FNAME"//客户名称
                            ), cusCond);
                            if (bd_customer != null && bd_customer.size() > 0) {//如果有这个客户的话
                                FCustomerID = VtuzxUtil.getString(bd_customer.get(0), "FNumber");
                            }
                            VtuzxMap FID = new VtuzxMap()
                                    .append("flagForFOwnerID", "100")
                                    .append("flagForFOwnerId", "100")
                                    .append("flagForFRetcustId", FCustomerID)
                                    .append("flagForFReceiveCustId", "100")
                                    .append("flagForFStockID", warehouseCode)
                                    .append("flagForFSaleOrgId", "100")
                                    .append("flagForFCustomerID", FCustomerID)
                                    .append("flagForFStockOrgId", "100")
                                    .append("flagForFReceiverID", FCustomerID)
                                    .append("flagForFSettleID", FCustomerID)
                                    .append("flagForFSettleOrgId", "100")
                                    .append("flagForFSettleCustId", FCustomerID)
                                    .append("flagForFPayCustId", FCustomerID)
                                    .append("flagForFPayerID", FCustomerID)
                                    .append("flagForFOwnerIdHead", "100")
                                    .append("flagForFSaledeptid", "05")
                                    .append("priceMap", priceMap)
                                    .append("taxMap", taxMap);
                            syncKingdeeSaleReturnTask(clientYX, sale, goodsList, historyDoc, FID);
                        } else if (warehouseCode.equals("XQ03") && shopName.equals("杭州光年有限公司")) {
                            //step1
                            //新工厂 采购退
                            VtuzxMap FID1 = new VtuzxMap()
                                    .append("flagForFStockOrgId", "200")
                                    .append("flagForFRequireOrgId", "200")
                                    .append("flagForFPurchaseOrgId", "200")
                                    .append("flagForFSupplierID", "05.0002")
                                    .append("flagForFACCEPTORID", "05.0002")
                                    .append("flagForFSettleId", "05.0002")
                                    .append("flagForFCHARGEID", "05.0002")
                                    .append("flagForFOwnerIdHead", "200")
                                    .append("flagForFSettleOrgId", "200")
                                    .append("flagForFStockID", "001")
                                    .append("priceMap", priceMap)
                                    .append("flagForFOwnerID", "200")
                                    .append("flagForFOwnerId", "200")
                                    .append("flagForFOWNERID", "200");
                            syncKingdeeRefundXYTask(clientYX, sale, materialMap, goodsList, historyDoc, FID1);
                            //step2
                            //跨组织销售退货单 销售组织:100 库存组织及货主:200
                            String FCustomerID = "C202305300092";
                            VtuzxMap FID2 = new VtuzxMap()
                                    .append("flagForFOwnerID", "200")
                                    .append("flagForFOwnerId", "200")
                                    .append("flagForFOWNERID", "200")
                                    .append("flagForFRetcustId", FCustomerID)
                                    .append("flagForFReceiveCustId", "200")
                                    .append("flagForFStockID", "001")
                                    //销售组织FSaleOrgId:100
                                    .append("flagForFSaleOrgId", "100")
                                    .append("flagForFCustomerID", FCustomerID)
                                    //库存组织FStockOrgId:200
                                    .append("flagForFStockOrgId", "200")
                                    .append("flagForFReceiverID", FCustomerID)
                                    .append("flagForFSettleID", FCustomerID)
                                    .append("flagForFSettleOrgId", "100")
                                    .append("flagForFSettleCustId", FCustomerID)
                                    .append("flagForFPayCustId", FCustomerID)
                                    .append("flagForFPayerID", FCustomerID)
                                    //货主FOwnerIdHead:200
                                    .append("flagForFOwnerIdHead", "200")
                                    .append("flagForFSaledeptid", "18")
                                    .append("flagForBillChannel", "09")
                                    .append("priceMap", priceMap)
                                    .append("taxMap", taxMap);
                            syncKingdeeSaleReturnTask(clientYX, sale, goodsList, historyDoc, FID2);
                        } else {
                            _logger.info("不符合条件，不进行同步");
                        }
                    } else {
                        _logger.info("数量为0，不进行同步");
                    }
                    /*//如果方法有返回值,说明有问题
                    if (!VtuzxUtil.isEmpty(success)) {
                        historyDoc.append("success", false);
                        if (id == null) {
                            syncOrderDao.insertOne(historyDoc);
                        } else {
                            historyDoc.remove("_id");
                            historyDoc.append("updateUserId", userId);
                            historyDoc.append("updateUserName", userName);
                            syncOrderDao.updateById(id, historyDoc);
                        }
                        String _id = VtuzxUtil.getString(sale, "_id");
                        syncTaskDao.updateById(_id, new Document("isUpload", "no"));
                    } else {
                        historyDoc.append("success", true);
                        if (id == null) {
                            syncOrderDao.insertOne(historyDoc);
                        } else {
                            historyDoc.remove("id");
                            historyDoc.remove("createTime");
                            historyDoc.remove("updateTime");
                            //不知道为啥remove删除字段后还有信息
                            historyDoc.append("message", "");
                            historyDoc.append("updateUserId", userId);
                            historyDoc.append("updateUserName", userName);
                            syncOrderDao.updateById(id, historyDoc);
                        }
                        String _id = VtuzxUtil.getString(sale, "_id");
                        syncTaskDao.updateById(_id, new Document("isUpload", "yes"));
                    }*/
                    historyDoc.append("success", true);
                    if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {
                        historyDoc.remove("_id");
                        historyDoc.remove("createTime");
                        historyDoc.remove("updateTime");
                        historyDoc.remove("message");
                        syncOrderDao.updateById(id, historyDoc);
                    }
                } catch (Exception e) {
                    /*if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {
                        historyDoc.remove("_id");
                        historyDoc.remove("createTime");
                        historyDoc.remove("updateTime");
                        syncOrderDao.updateById(id, historyDoc);
                    }
                    _logger.info(e.getMessage());*/
                    historyDoc.append("syncTaskSale", false).append("message", e.getMessage()).append("success", false);
                    if (id == null) {
                        syncOrderDao.insertOne(historyDoc);
                    } else {
                        historyDoc.remove("_id");
                        historyDoc.remove("createTime");
                        historyDoc.remove("updateTime");
                        syncOrderDao.updateById(id, historyDoc);
                    }
                    throw e;
                }
            }
        }
    }

    /**
     * 自采品拆分方法
     */
    private void handleSelfProductSplit(Document data, Document historyDoc, VtuzxKingdeeCloudClient clientYX) throws Exception {
        //销售单部分
        if (!VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "tradeNo"))) {
            Document sale = data;
            String fSaledeptid = "";
            String departName = "";
            String tradeNo = sale.getString("tradeNo");
            List<String> materialNoList = new ArrayList<>();//物料编码集合
            List<Document> goodsList = VtuzxUtil.getObject(sale, "goodsDetail");
            for (Document goodsMap : goodsList) {
                String materialNo = VtuzxUtil.getString(goodsMap, "goodsNo");
                if (!materialNoList.contains(materialNo)) {
                    materialNoList.add(materialNo);
                }
            }
            VtuzxMap materialMap = new VtuzxMap();
            Iterator<Document> materialItr = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
            while (materialItr.hasNext()) {
                Document mtr = materialItr.next();
                VtuzxMap mtrMap = new VtuzxMap();
                String materialNumber = VtuzxUtil.getString(mtr, "fNumber");
                String materialName = VtuzxUtil.getString(mtr, "fName");
                String fSpecification = VtuzxUtil.getString(mtr, "fSpecification");
                String fBaseUnitIdFName = VtuzxUtil.getString(mtr, "fBaseUnitIdFName");
                mtrMap.append("materialName", materialName);
                mtrMap.append("materialSpec", fSpecification);
                mtrMap.append("unit", fBaseUnitIdFName);
                mtrMap.append("materialNo", materialNumber);
                materialMap.append(materialNumber, mtrMap);
            }
            Map<String, Object> goodsMap = new LinkedHashMap<>();//k:物料编码 v:对应的值(goodsList里数量都是一，整理到一起)
            for (Map<String, Object> goods : goodsList) {
                Document doc = new Document(goods);
                String goodsNo = VtuzxUtil.getString(doc, "goodsNo");
                Document getGoods = (Document) goodsMap.get(goodsNo);
                if (!materialNoList.contains(goodsNo)) {
                    materialNoList.add(goodsNo);
                }
                if (VtuzxUtil.isEmpty(getGoods)) {//如果是空的直接添加
                    goodsMap.put(goodsNo, doc);
                } else {
                    int skuCount = VtuzxUtil.getInt(doc, "skuCount");
                    int skuNowCount = VtuzxUtil.getInt(getGoods, "skuCount");
                    doc.replace("skuCount", skuCount + skuNowCount);
                    goodsMap.put(goodsNo, doc);
                }
            }
            Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
            Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
            //查询物料表获取税率信息
            Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
            while (materials.hasNext()) {
                Document materialDoc = materials.next();
                String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
                String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
                String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
                String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
                String substring = "";
                if (fTaxRateName.startsWith("零")) {
                    substring = "0";
                } else {
                    substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
                }
                taxMap.put(materialNo, Double.parseDouble(substring));
                unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
            }
            //查询价目表获取价格信息
            Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
            Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
            while (priceItr.hasNext()) {
                Document priceDoc = priceItr.next();
                String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
                Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");
                priceMap.put(materialNo, currentPrice);
            }

/*        Document historyDoc = syncOrderDao.findOne(Criteria.where("billTaskNo").is(tradeNo));
        ObjectId id = null;
        if (historyDoc == null) {
            historyDoc = new Document("billTaskNo", tradeNo);
        } else {
            id = VtuzxUtil.getObject(historyDoc, "_id");
        }
        historyDoc.append("billTaskNo", tradeNo);
        historyDoc.append("userId", userId);
        historyDoc.append("userName", userName);
        historyDoc.append("source", "source");
        historyDoc.append("data", goodsList);
        historyDoc.append("event", "innerSetter");*/
            double tradeCount = VtuzxUtil.getDouble(sale, "tradeCount");
            //从销售单sale中获取goodsDetail集合
            List<Document> goodsDetails = VtuzxUtil.getObject(sale, "goodsDetail");
            if (goodsDetails == null) {
                throw new VtuzxException("销售单" + tradeNo + "中缺少商品明细");
            }
            List<Document> selfItems = new ArrayList<>();
            List<Document> nonSelfItems = new ArrayList<>();
            //遍历商品明细，分离自采品和非自采品
            for (Document goodsDetail : goodsDetails) {
                String goodsNo = VtuzxUtil.getString(goodsDetail, "goodsNo");
                if (selfProductDao.isSelfProduct(goodsNo)) {
                    selfItems.add(goodsDetail);
                } else {
                    nonSelfItems.add(goodsDetail);
                }
            }
            //如果非自采品不为空，处理非自采品（内部结算）
            if (!VtuzxUtil.isEmpty(nonSelfItems)) {
                //构建销售单副本
                Document nonSelfSale = new Document(sale);
                //清空副本中的物料明细
                nonSelfSale.put("goodsDetail", null);
                //获得非自采品的materialMap
                List<String> nonSelfMaterialNoList = new ArrayList<>();//物料编码集合
                //遍历物料集合
                for (Document nonSelfGoodsMap : nonSelfItems) {
                    //添加物料编码集合
                    String materialNo = VtuzxUtil.getString(nonSelfGoodsMap, "GoodsNo");
                    if (!nonSelfMaterialNoList.contains(materialNo)) {
                        nonSelfMaterialNoList.add(materialNo);
                    }
                }
                VtuzxMap nonSelfMaterialMap = new VtuzxMap();
                //根据物料编码集合查询物料信息
                Iterator<Document> nonSelfMaterialItr = materialDao.findList(Criteria.where("fNumber").in(nonSelfMaterialNoList), null, 0, 0);
                while (nonSelfMaterialItr.hasNext()) {
                    Document mtr = nonSelfMaterialItr.next();
                    VtuzxMap mtrMap = new VtuzxMap();
                    String materialNumber = VtuzxUtil.getString(mtr, "fNumber");
                    String materialName = VtuzxUtil.getString(mtr, "fName");
                    String fSpecification = VtuzxUtil.getString(mtr, "fSpecification");
                    String fBaseUnitIdFName = VtuzxUtil.getString(mtr, "fBaseUnitIdFName");
                    mtrMap.append("materialName", materialName);
                    mtrMap.append("materialSpec", fSpecification);
                    mtrMap.append("unit", fBaseUnitIdFName);
                    mtrMap.append("materialNo", materialNumber);
                    nonSelfMaterialMap.append(materialNumber, mtrMap);
                }
                //组织间结算
                if (tradeCount > 0) {
                    //跨组织销售出库单 销售组织:100 发货组织及货主:200
                    VtuzxMap FID = new VtuzxMap()
                            .append("flagForFOwnerID", "200")
                            .append("flagForFStockID", "001")
                            //销售组织FSaleOrgId:100
                            .append("flagForFSaleOrgId", "100")
                            .append("flagForFCustomerID", "CUST0014")
                            //发货组织FStockOrgId:200
                            .append("flagForFStockOrgId", "200")
                            .append("flagForFReceiverID", "CUST0014")
                            .append("flagForFSettleID", "CUST0014")
                            .append("flagForFPayerID", "CUST0014")
                            //货主FOwnerIdHead:200
                            .append("flagForFOwnerIdHead", "200")
                            .append("priceMap", priceMap);
                    syncKingdeeSaleOutTask(clientYX, nonSelfSale, nonSelfMaterialMap, nonSelfItems, historyDoc, FID);
                } else if (tradeCount < 0) {
                    //step1
                    //新工厂 销售退
                    VtuzxMap FID1 = new VtuzxMap()
                            .append("flagForFSaleOrgId", "200")
                            .append("flagForFRetcustId", "CUST0014")
                            .append("flagForFStockOrgId", "200")
                            .append("flagForFReceiveCustId", "CUST0014")
                            .append("flagForFSettleCustId", "CUST0014")
                            .append("flagForFPayCustId", "CUST0014")
                            .append("flagForFSettleOrgId", "200")
                            .append("flagForFOwnerId", "200")
                            .append("flagForFStockID", "001");
                    syncKingdeeSaleReturnTask(clientYX, nonSelfSale, nonSelfItems, historyDoc, FID1);
                    //step2
                    //销售公司 采购退
                    VtuzxMap FID2 = new VtuzxMap()
                            .append("flagForFStockOrgId", "100")
                            .append("flagForFRequireOrgId", "100")
                            .append("flagForFPurchaseOrgId", "100")
                            .append("flagForFSupplierID", "05.0002")
                            .append("flagForFACCEPTORID", "05.0002")
                            .append("flagForFSettleId", "05.0002")
                            .append("flagForFCHARGEID", "05.0002")
                            .append("flagForFOwnerIdHead", "100")
                            .append("flagForFSettleOrgId", "100")
                            .append("flagForFStockID", "YXBBTQ01")
                            //.append("flagForFStockID", warehouseCode)
                            .append("flagForFOWNERID", "100");
                    syncKingdeeRefundXYTask(clientYX, nonSelfSale, nonSelfMaterialMap, nonSelfItems, historyDoc, FID2);
                } else {
                    _logger.info("数量为0，不进行同步");
                }
            }
            //如果自采品不为空，处理自采品
            if (!VtuzxUtil.isEmpty(selfItems)) {
                //构建销售单副本
                Document selfSale = new Document(sale);
                //清空副本中的物料明细
                selfSale.put("goodsDetail", null);
                //添加自采品明细到副本
                selfSale.put("goodsDetail", selfItems);
                //获得自采品的materialMap
                List<String> selfMaterialNoList = new ArrayList<>();//物料编码集合
                //遍历物料集合
                for (Document selfGoodsMap : selfItems) {
                    //添加物料编码集合
                    String materialNo = VtuzxUtil.getString(selfGoodsMap, "GoodsNo");
                    if (!selfMaterialNoList.contains(materialNo)) {
                        selfMaterialNoList.add(materialNo);
                    }
                }
                VtuzxMap selfMaterialMap = new VtuzxMap();
                //根据物料编码集合查询物料信息
                Iterator<Document> selfMaterialItr = materialDao.findList(Criteria.where("fNumber").in(selfMaterialNoList), null, 0, 0);
                while (selfMaterialItr.hasNext()) {
                    Document mtr = selfMaterialItr.next();
                    VtuzxMap mtrMap = new VtuzxMap();
                    String materialNumber = VtuzxUtil.getString(mtr, "fNumber");
                    String materialName = VtuzxUtil.getString(mtr, "fName");
                    String fSpecification = VtuzxUtil.getString(mtr, "fSpecification");
                    String fBaseUnitIdFName = VtuzxUtil.getString(mtr, "fBaseUnitIdFName");
                    mtrMap.append("materialName", materialName);
                    mtrMap.append("materialSpec", fSpecification);
                    mtrMap.append("unit", fBaseUnitIdFName);
                    mtrMap.append("materialNo", materialNumber);
                    selfMaterialMap.append(materialNumber, mtrMap);
                }
                if (tradeCount > 0) {
                    //销售公司 销售出
                    VtuzxMap FID = new VtuzxMap()
                            /*.append("flagForFOwnerID", "100")
                            .append("flagForFStockID", warehouseCode)
                            .append("flagForFSaleOrgId", "100")
                            .append("flagForFCustomerID", FCustomerID)
                            .append("flagForFStockOrgId", "100")
                            .append("flagForFReceiverID", FCustomerID)
                            .append("flagForFSettleID", FCustomerID)
                            .append("flagForFPayerID", FCustomerID);*/
                            .append("flagForFOwnerID", "100")
                            .append("flagForFStockID", "YXBBTQ01")
                            .append("flagForFSaleOrgId", "100")
                            .append("flagForFCustomerID", "03.01.017")
                            .append("flagForFStockOrgId", "100")
                            .append("flagForFReceiverID", "03.01.017")
                            .append("flagForFSettleID", "03.01.017")
                            .append("flagForFPayerID", "03.01.017")
                            .append("priceMap", priceMap);
                    syncKingdeeSaleOutTask(clientYX, selfSale, selfMaterialMap, selfItems, historyDoc, FID);
                } else if (tradeCount < 0) {
                    //销售公司 销售退
                    VtuzxMap FID = new VtuzxMap()
                            /*.append("flagFSaleOrgId", "100")
                            .append("flagFRetcustId", FCustomerID)
                            .append("flagFStockOrgId", "100")
                            .append("flagFReceiveCustId", FCustomerID)
                            .append("flagFSettleCustId", FCustomerID)
                            .append("flagFPayCustId", FCustomerID)
                            .append("flagFSettleOrgId", "100")
                            .append("flagFOwnerId", "100")
                            .append("flagFStockId", warehouseCode);*/
                            .append("flagFSaleOrgId", "100")
                            .append("flagFRetcustId", "03.01.017")
                            .append("flagFStockOrgId", "100")
                            .append("flagFReceiveCustId", "03.01.017")
                            .append("flagFSettleCustId", "03.01.017")
                            .append("flagFPayCustId", "03.01.017")
                            .append("flagFSettleOrgId", "100")
                            .append("flagFOwnerId", "100")
                            .append("flagFStockId", "YXBBTQ01")
                            .append("priceMap", priceMap);
                    syncKingdeeSaleOutTask(clientYX, selfSale, selfMaterialMap, selfItems, historyDoc, FID);
                } else {
                    _logger.info("数量为0，不进行同步");
                }
            }
            //调拨单部分
        } else if (!VtuzxUtil.isEmpty(VtuzxUtil.getString(data, "allocateNo"))) {
            Document allocation = data;
            String allocateNo = allocation.getString("allocateNo");
            String source = VtuzxUtil.getString(allocation, "outWarehouseCode");
            String target = VtuzxUtil.getString(allocation, "intWarehouseCode");
            List<String> materialNoList = new ArrayList<>();//物料编码集合
            List<Document> goodsList = VtuzxUtil.getObject(allocation, "stockAllocateDetailViews");
            for (Document goodsMap : goodsList) {
                String materialNo = VtuzxUtil.getString(goodsMap, "goodsNo");
                if (!materialNoList.contains(materialNo)) {
                    materialNoList.add(materialNo);
                }
            }
            VtuzxMap materialMap = new VtuzxMap();
            Iterator<Document> materialItr = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
            while (materialItr.hasNext()) {
                Document mtr = materialItr.next();
                VtuzxMap mtrMap = new VtuzxMap();
                String materialNumber = VtuzxUtil.getString(mtr, "fNumber");
                String materialName = VtuzxUtil.getString(mtr, "fName");
                String fSpecification = VtuzxUtil.getString(mtr, "fSpecification");
                String fBaseUnitIdFName = VtuzxUtil.getString(mtr, "fBaseUnitIdFName");
                mtrMap.append("materialName", materialName);
                mtrMap.append("materialSpec", fSpecification);
                mtrMap.append("unit", fBaseUnitIdFName);
                mtrMap.append("materialNo", materialNumber);
                materialMap.append(materialNumber, mtrMap);
            }
            Map<String, Object> taxMap = new HashMap<>();//key:物料编码 value:税率
            Map<String, Object> unitMap = new HashMap<>();//key:单位名称 value : 单位id
            //查询物料表获取税率信息
            Iterator<Document> materials = materialDao.findList(Criteria.where("fNumber").in(materialNoList), null, 0, 0);
            while (materials.hasNext()) {
                Document materialDoc = materials.next();
                String materialNo = VtuzxUtil.getString(materialDoc, "fNumber");
                String fTaxRateName = VtuzxUtil.getString(materialDoc, "fTaxRateName");//税率
                String fBaseUnitIdNumber = VtuzxUtil.getString(materialDoc, "fBaseUnitIdNumber");//单位id
                String fBaseUnitIdFName = VtuzxUtil.getString(materialDoc, "fBaseUnitIdFName");//单位名称
                String substring = "";
                if (fTaxRateName.startsWith("零")) {
                    substring = "0";
                } else {
                    substring = fTaxRateName.substring(0, fTaxRateName.indexOf("%"));
                }
                taxMap.put(materialNo, Double.parseDouble(substring));
                unitMap.put(fBaseUnitIdFName, fBaseUnitIdNumber);
            }
            //查询价目表获取价格信息
            Iterator<Document> priceItr = priceListDao.findList(Criteria.where("materialNo").in(materialNoList), null, 0, 0);
            Map<String, Object> priceMap = new HashMap<>();//key : 物料编码 val:初始供货价
            while (priceItr.hasNext()) {
                Document priceDoc = priceItr.next();
                String materialNo = VtuzxUtil.getString(priceDoc, "materialNo");
                Double currentPrice = VtuzxUtil.getDouble(priceDoc, "currentPrice");
                priceMap.put(materialNo, currentPrice);
            }
            //从调拨单allocation中获取goodsDetail集合
            List<Document> goodsDetails = VtuzxUtil.getObject(allocation, "stockAllocateDetailViews");
            if (goodsDetails == null) {
                throw new VtuzxException("调拨单" + allocateNo + "中缺少商品明细");
            }
            List<Document> selfItems = new ArrayList<>();
            List<Document> nonSelfItems = new ArrayList<>();
            //遍历商品明细，分离自采品和非自采品
            for (Document goodsDetail : goodsDetails) {
                String goodsNo = VtuzxUtil.getString(goodsDetail, "goodsNo");
                if (selfProductDao.isSelfProduct(goodsNo)) {
                    selfItems.add(goodsDetail);
                } else {
                    nonSelfItems.add(goodsDetail);
                }
            }
            //如果非自采品不为空，处理非自采品
            if (!VtuzxUtil.isEmpty(nonSelfItems)) {
                //构建调拨单副本
                Document nonSelfSale = new Document(allocation);
                //清空副本中的物料明细
                nonSelfSale.put("stockAllocateDetailViews", null);
                //添加非自采品明细到副本
                nonSelfSale.put("stockAllocateDetailViews", nonSelfItems);
                //获得非自采品的materialMap
                List<String> nonSelfMaterialNoList = new ArrayList<>();//物料编码集合
                for (Document nonSelfGoodsMap : nonSelfItems) {
                    String materialNo = VtuzxUtil.getString(nonSelfGoodsMap, "goodsNo");
                    if (!nonSelfMaterialNoList.contains(materialNo)) {
                        nonSelfMaterialNoList.add(materialNo);
                    }
                }
                VtuzxMap nonSelfMaterialMap = new VtuzxMap();
                Iterator<Document> nonSelfMaterialItr = materialDao.findList(Criteria.where("fNumber").in(nonSelfMaterialNoList), null, 0, 0);
                while (nonSelfMaterialItr.hasNext()) {
                    Document mtr = nonSelfMaterialItr.next();
                    VtuzxMap mtrMap = new VtuzxMap();
                    String materialNumber = VtuzxUtil.getString(mtr, "fNumber");
                    String materialName = VtuzxUtil.getString(mtr, "fName");
                    String fSpecification = VtuzxUtil.getString(mtr, "fSpecification");
                    String fBaseUnitIdFName = VtuzxUtil.getString(mtr, "fBaseUnitIdFName");
                    mtrMap.append("materialName", materialName);
                    mtrMap.append("materialSpec", fSpecification);
                    mtrMap.append("unit", fBaseUnitIdFName);
                    mtrMap.append("materialNo", materialNumber);
                    nonSelfMaterialMap.append(materialNumber, mtrMap);
                }
                if (target.equals("XQBB00067") || target.equals("XQ03")) {
                    //(XQ03)非自采品的部分,传销售公司（跨组织）直接调拨单
                    //销售公司 → 新工厂 （跨组织）直接调拨单
                    VtuzxMap FID = new VtuzxMap()
                            .append("flagForFSrcStockID", source)
                            .append("flagForFDestStockId", "001")
                            .append("flagForFSettleOrgId", "100")
                            .append("flagForFSaleOrgId", "100")
                            .append("flagForFStockOutOrgId", "100")
                            .append("flagForFOwnerOutIdHead", "100")
                            .append("flagForFStockOrgId", "200")
                            .append("flagForFOwnerIdHead", "200")
                            .append("flagForFOwnerOutId", "100")
                            .append("flagForFOwnerId", "200")
                            .append("flagForFKeeperId", "200")
                            .append("flagForFKeeperOutId", "100")
                            .append("priceMap", priceMap);
                    syncKingdeeInnerAllocationTask(clientYX, nonSelfSale, nonSelfItems, historyDoc, FID);
                    /*} else if (target.equals("XQ03")) {*/
                    /*//销售公司 销售退
                    String fSaledeptid = "";
                    String FNumber = yxCustomerDao.getCodeByCode(source);
                    String outWarehouseName = VtuzxUtil.getString(nonSelfSale, "outWarehouseName");
                    String departName = outWarehouseName.substring(0, outWarehouseName.indexOf("-"));
                    if (!VtuzxUtil.isEmpty(departName)) {//如果吉客云部门名称不为空，查询金蝶部门id
                        //查询发货部门id
                        String cond = String.format("FName = '%s' and FForbidStatus ='%s'", departName, "A");
                        List<VtuzxMap> bd_department = kingdeeService.query(clientYX, "BD_Department", new VtuzxArrayList<>(
                                "FNumber",//=部门编码
                                "FNAME"//部门
                        ), cond);
                        if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                            fSaledeptid = (String) bd_department.get(0).get("FNumber");
                        }
                    }
                    VtuzxMap FID = new VtuzxMap()
                            .append("flagForFOwnerID", "100")
                            .append("flagForFRetcustId", FNumber)
                            .append("flagForFReceiveCustId", FNumber)
                            .append("flagForFStockID", "BN001")
                            .append("flagForFSaleOrgId", "100")
                            .append("flagForFCustomerID", FNumber)
                            .append("flagForFStockOrgId", "100")
                            .append("flagForFReceiverID", FNumber)
                            .append("flagForFSettleID", FNumber)
                            .append("flagForFSettleOrgId", "100")
                            .append("flagForFSettleCustId", FNumber)
                            .append("flagForFPayCustId", FNumber)
                            .append("flagForFPayerID", FNumber)
                            .append("flagForFOwnerIdHead", "100")
                            .append("flagForFSaledeptid", fSaledeptid)
                            .append("priceMap", priceMap);
                    syncKingdeeSaleReturnTask(clientYX, nonSelfSale, nonSelfItems, historyDoc, FID);*/
                    /*//非自采品的部分,传新工厂退货仓
                    //新工厂 销售退
                    VtuzxMap FID = new VtuzxMap()
                            .append("flagForFSaleOrgId", "200")
                            .append("flagForFRetcustId", "CUST0014")
                            .append("flagForFStockOrgId", "200")
                            .append("flagForFReceiveCustId", "CUST0014")
                            .append("flagForFSettleCustId", "CUST0014")
                            .append("flagForFPayCustId", "CUST0014")
                            .append("flagForFSettleOrgId", "200")
                            .append("flagForFOwnerId", "200")
                            .append("flagForFStockId", "001")
                            .append("flagForFStockID", "001")
                            .append("flagForFOwnerIdHead", "100")
                            .append("flagForFSaledeptid", "02")
                            .append("priceMap", priceMap);
                    syncKingdeeSaleReturnTask(clientYX, nonSelfSale, nonSelfItems, historyDoc, FID);*/
                } else {
                    throw new Exception("数据异常");
                }
            }
            //如果自采品不为空，处理自采品
            if (!VtuzxUtil.isEmpty(selfItems)) {
                //构建调拨单副本
                Document selfSale = new Document(allocation);
                //清空副本中的物料明细
                selfSale.put("stockAllocateDetailViews", null);
                //添加自采品明细到副本
                selfSale.put("stockAllocateDetailViews", selfItems);
                String FNumber = yxCustomerDao.getCodeByCode(source);
                //获得自采品的materialMap
                List<String> selfMaterialNoList = new ArrayList<>();//物料编码集合
                for (Document selfGoodsMap : selfItems) {
                    String materialNo = VtuzxUtil.getString(selfGoodsMap, "goodsNo");
                    if (!selfMaterialNoList.contains(materialNo)) {
                        selfMaterialNoList.add(materialNo);
                    }
                }
                VtuzxMap selfMaterialMap = new VtuzxMap();
                Iterator<Document> selfMaterialItr = materialDao.findList(Criteria.where("fNumber").in(selfMaterialNoList), null, 0, 0);
                while (selfMaterialItr.hasNext()) {
                    Document mtr = selfMaterialItr.next();
                    VtuzxMap mtrMap = new VtuzxMap();
                    String materialNumber = VtuzxUtil.getString(mtr, "fNumber");
                    String materialName = VtuzxUtil.getString(mtr, "fName");
                    String fSpecification = VtuzxUtil.getString(mtr, "fSpecification");
                    String fBaseUnitIdFName = VtuzxUtil.getString(mtr, "fBaseUnitIdFName");
                    mtrMap.append("materialName", materialName);
                    mtrMap.append("materialSpec", fSpecification);
                    mtrMap.append("unit", fBaseUnitIdFName);
                    mtrMap.append("materialNo", materialNumber);
                    selfMaterialMap.append(materialNumber, mtrMap);
                }
                /*//销售公司 销售退
                String fSaledeptid = "";
                String outWarehouseName = VtuzxUtil.getString(selfSale, "outWarehouseName");
                String departName = outWarehouseName.substring(0, outWarehouseName.indexOf("-"));
                if (!VtuzxUtil.isEmpty(departName)) {//如果吉客云部门名称不为空，查询金蝶部门id
                    //查询发货部门id
                    String cond = String.format("FName = '%s' and FForbidStatus ='%s'", departName, "A");
                    List<VtuzxMap> bd_department = kingdeeService.query(clientYX, "BD_Department", new VtuzxArrayList<>(
                            "FNumber",//=部门编码
                            "FNAME"//部门
                    ), cond);
                    if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                        fSaledeptid = (String) bd_department.get(0).get("FNumber");
                    }
                }
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFOwnerID", "100")
                        .append("flagForFRetcustId", FNumber)
                        .append("flagForFReceiveCustId", FNumber)
                        .append("flagForFStockID", "YXJDP01")
                        .append("flagForFSaleOrgId", "100")
                        .append("flagForFCustomerID", FNumber)
                        .append("flagForFStockOrgId", "100")
                        .append("flagForFReceiverID", FNumber)
                        .append("flagForFSettleID", FNumber)
                        .append("flagForFSettleOrgId", "100")
                        .append("flagForFSettleCustId", FNumber)
                        .append("flagForFPayCustId", FNumber)
                        .append("flagForFPayerID", FNumber)
                        .append("flagForFOwnerIdHead", "100")
                        .append("flagForFSaledeptid", fSaledeptid)
                        .append("priceMap", priceMap);
                syncKingdeeSaleReturnTask(clientYX, selfSale, selfItems, historyDoc, FID);*/
                //自采品的部分,传百年退货仓 BN001
                //（组织内）直接调拨单
                String FOUTDEPTID = "";
                String FINDEPTID = "05";
                String outWarehouseName = VtuzxUtil.getString(selfSale, "outWarehouseName");
//                String inWarehouseName = VtuzxUtil.getString(selfSale, "inWarehouseName");
                String FOUTDEPTName = outWarehouseName.substring(0, outWarehouseName.indexOf("-"));
//                String FINDEPTName = inWarehouseName.substring(0, inWarehouseName.indexOf("-"));
                if (!VtuzxUtil.isEmpty(FOUTDEPTName)) {//如果吉客云部门名称不为空，查询金蝶部门id
                    //查询发货部门id
                    String cond = String.format("FName = '%s' and FForbidStatus ='%s'", FOUTDEPTName, "A");
                    List<VtuzxMap> bd_department = kingdeeService.query(clientYX, "BD_Department", new VtuzxArrayList<>(
                            "FNumber",//=部门编码
                            "FNAME"//部门
                    ), cond);
                    if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                        //调出部门
                        FOUTDEPTID = (String) bd_department.get(0).get("FNumber");
                    }
                }
                /*if (!VtuzxUtil.isEmpty(FINDEPTName)) {//如果吉客云部门名称不为空，查询金蝶部门id
                    //查询收货部门id
                    String cond = String.format("FName = '%s' and FForbidStatus ='%s'", FINDEPTName, "A");
                    List<VtuzxMap> bd_department = kingdeeService.query(clientYX, "BD_Department", new VtuzxArrayList<>(
                            "FNumber",//=部门编码
                            "FNAME"//部门
                    ), cond);
                    if (bd_department != null && bd_department.size() > 0) {//如果有这个部门的话
                        //调入部门
                        FINDEPTID = (String) bd_department.get(0).get("FNumber");
                    }
                }*/
                VtuzxMap FID = new VtuzxMap()
                        .append("flagForFSrcStockID", source)
                        .append("flagForFDestStockId", "BN001")
                        .append("flagForFSettleOrgId", "100")
                        .append("flagForFSaleOrgId", "100")
                        .append("flagForFStockOutOrgId", "100")
                        .append("flagForFOwnerOutIdHead", "100")
                        .append("flagForFStockOrgId", "100")
                        .append("flagForFOwnerIdHead", "100")
                        .append("flagForFOwnerOutId", "100")
                        .append("flagForFOwnerId", "100")
                        .append("flagForFKeeperId", "100")
                        .append("flagForFKeeperOutId", "100")
                        .append("flagForFOUTDEPTID", FOUTDEPTID)
                        .append("flagForFINDEPTID", FINDEPTID)
                        .append("flagForFTransferBizType", "InnerOrgTransfer")
                        .append("priceMap", priceMap);
                syncKingdeeInnerAllocationTask(clientYX, selfSale, selfItems, historyDoc, FID);
            } else {
                throw new Exception("未知的单据类型");
            }
        }
    }

    /**
     * 校验并修复数据
     */
    public void checkAndFixInconsistentData() {
        String collName = "t_sync_task";
        String historyCollName = "t_sync_task_history";
        //构建聚合管道，查找历史表中存在但待同步表未删除的数据
        List<Document> pipeline = Arrays.asList(
                new Document("$lookup", new Document()
                        .append("from", collName)  //关联待同步表
                        .append("localField", "billTaskNo")  //历史表的关联字段
                        .append("foreignField", "billTaskNo")  //待同步表的关联字段
                        .append("as", "existingTasks")  //结果字段名
                ),
                new Document("$match", new Document()
                        .append("existingTasks.0", new Document("$exists", true))  //筛选有关联记录的数据
                )
        );
        //执行聚合查询
        Iterator<Document> iterator = syncTaskHistoryDao.aggregate(historyCollName, pipeline);
        List<Document> inconsistentData = new ArrayList<>();
        while (iterator.hasNext()) {
            inconsistentData.add(iterator.next());
        }
        //删除多余数据
        if (!inconsistentData.isEmpty()) {
            _logger.warn("发现 {} 条多余数据，开始修复...", inconsistentData.size());
            for (Document inconsistentDoc : inconsistentData) {
                String billTaskNo = inconsistentDoc.getString("billTaskNo");
                //删除待同步表中残留的数据
                Criteria cond = Criteria.where("billTaskNo").is(billTaskNo);
                syncTaskDao.deleteOne(collName, cond, null);
                _logger.info("删除多余数据：billTaskNo=" + billTaskNo);
            }
        }
    }

    /**
     * 配置同步时间
     */
    @Override
    public void uploadSyncTime(ObjectId userId, String userName, Map<String, Object> param) throws VtuzxException {
        //用标识符查找唯一一条数据
        Criteria cond = Criteria.where("syncTimeFlag").is("timeFlag");
        String syncTime = VtuzxUtil.getString(param, "value");
        try{
            //更新天数
            syncTimeDao.findOneAndUpdate(cond, new Document("syncTime", syncTime));
            syncTimeDao.findOneAndUpdate(cond, new Document("updateTime", new Date()));
        } catch (Exception e) {
            _logger.info("保存失败:" + e.getMessage());
        }
    }

    /**
     * 获取新工厂(百年)还未生成调拨的调拨单
     * @param userId
     * @param param
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public VtuzxMap getBainianAllocationList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String allocateNo = VtuzxUtil.getString(param, "allocateNo");
        Criteria cond = new Criteria();
        cond.and("isUpload").is(false);
        if (!VtuzxUtil.isEmpty(allocateNo)) {
            cond.and("billNo").regex(allocateNo);
        }

        VtuzxPage page = bainianAllocationDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("allocateNo", VtuzxUtil.getString(doc, "allocateNo"))//单据类型
                .append("outWarehouseName", VtuzxUtil.getString(doc, "outWarehouseName"))
                .append("intWarehouseName", VtuzxUtil.getString(doc, "intWarehouseName"))
                .append("companyName", VtuzxUtil.getString(doc, "companyName"))//
//                .append("allocateTypeName", VtuzxUtil.formatYmdHmsF(new Date(Long.parseLong(VtuzxUtil.getString(doc, "gmtCreate")))))
                .append("memo", VtuzxUtil.getString(doc, "memo")));

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    /**
     * 获取百年调拨详情
     * @param userId
     * @param billNoList
     * @return
     * @throws VtuzxException
     */
    @Override
    public VtuzxMap getBaiNianAllocationDetail(ObjectId userId, List<String> billNoList) throws Exception {
        List<Map<String,Object>> detailList = new ArrayList<>();//明细集合
        Iterator<Document> allocateItr = bainianAllocationDao.findList(Criteria.where("allocateNo").in(billNoList), null, 0, 0);
        while (allocateItr.hasNext()){
            Document allocateDoc = allocateItr.next();
            List<Map<String,Object>> stockAllocateDetailViews = VtuzxUtil.getObject(allocateDoc,"stockAllocateDetailViews");
            detailList.addAll(stockAllocateDetailViews);
        }
        //循环取出所有条码，然后查询吉客云库存信息,条码可以批量查询，
        //大连总仓map key:条码 val:库存
        //委外仓map key:条码 val:库存
        //大新工厂总仓 key:条码 val:库存
        List<String> skuList = new ArrayList<>();
        for (Map<String,Object> data : detailList){
            String skuBarcode = VtuzxUtil.getString(data,"skuBarcode");
            if (!skuList.contains(skuBarcode)){
                skuList.add(skuBarcode);
            }
        }
        Map<String, Object> xinMap = new HashMap<>();
        Map<String, Object> weiMap = new HashMap<>();
        Map<String, Object> daMap = new HashMap<>();
        try {
            xinMap = syncAllocation("XQBB00066", skuList, 0);
            daMap = syncAllocation("XQWG00101", skuList, 0);
            weiMap = syncAllocation("XQBB00068", skuList, 0);
        } catch (Exception e) {
            throw new VtuzxException(e.getMessage());
        }
        //计算数量分配
        for (Map<String,Object> data : detailList ){
            String goodsNo = VtuzxUtil.getString(data,"goodsNo");
            double skuCount = VtuzxUtil.getDouble(data,"skuCount");//需要的调拨数量
            if (skuCount <= 0){
                continue;
            }
            double xinCount = VtuzxUtil.getDouble(xinMap,goodsNo);//新工厂库存数量
            double weiCount = VtuzxUtil.getDouble(weiMap,goodsNo);//委外仓库存数量
            double daCount = VtuzxUtil.getDouble(daMap,goodsNo);//大连总仓库存数量
            double needQty = skuCount;
            double xinUse =0.0, weiUse = 0.0, daUse = 0.0;

            // 分配中使用的库存（负库存一律按 0 参与）
            double xinAvail = xinCount > 0 ? xinCount : 0;
            double weiAvail = weiCount > 0 ? weiCount : 0;


            // 1) 新工厂库存 > 0 才能参与分配
            if (xinAvail > 0) {
                if (xinAvail >= needQty) {
                    xinUse = needQty;
                    needQty = 0;
                } else {
                    xinUse = xinAvail;
                    needQty -= xinAvail;
                }
            }

            // 2) 委外仓
            if (needQty > 0 && weiAvail > 0) {
                if (weiAvail >= needQty) {
                    weiUse = needQty;
                    needQty = 0;
                } else {
                    weiUse = weiAvail;
                    needQty -= weiAvail;
                }
            }

            //大连总仓（可负库存）兜底
            if (needQty > 0) {
                daUse = needQty; // 允许负库存，所以直接全部给它
                needQty = 0;
            }
            // 新工厂库存大于 0 才扣减，否则保持原负值
            if (xinCount > 0) {
                xinMap.put(goodsNo, xinCount - xinUse);
            }

            // 委外仓库存大于 0 才扣减，否则保持原负值
            if (weiCount > 0) {
                weiMap.put(goodsNo, weiCount - weiUse);
            }
            // 大连总仓允许负库存，所以不用限制为 >=0
            daMap.put(goodsNo, daCount - daUse);
            // 回填明细展示字段（分配前库存 + 本次使用）
            data.put("xinCount", xinCount);
            data.put("weiCount", weiCount);
            data.put("daCount", daCount);

            data.put("xinUse", xinUse);
            data.put("weiUse", weiUse);
            data.put("daUse", daUse);

        }

        VtuzxMap dataMap = new VtuzxMap();
        dataMap.append("datalist",detailList);
        return dataMap;
    }

    @Override
    public Map<String, Object> syncAllocation(String stockNo, List<String> skuNoList, int pageIndex) throws Exception {
        Map<String,Object> skuMap = new HashMap<>();
        if (skuNoList == null || skuNoList.isEmpty()) {
            return skuMap;
        }

        Document storeDoc = storeTokenDao.findOne(Criteria.where("type").is("kingdee"));

        // 分批拼接，每批不超过1000字符
        List<List<String>> batchList = splitListByStringLength(skuNoList, 1000, ",");

        for (List<String> batchSkuList : batchList) {
            String skuToStr = String.join(",", batchSkuList);

            VtuzxMap customerMap = jiKeYunApiService.skuList(storeDoc,
                    new VtuzxMap("pageSize", 50)
                            .append("warehouseCode", stockNo)
                            .append("skuBarcode", skuToStr)
                            .append("cols","currentQuantity,availableQuantity,mainBarcode")
                            .append("pageIndex", pageIndex));

            Map<String, Object> result = VtuzxUtil.getObject(customerMap, "result");
            List<Map<String, Object>> stockAllocateList = VtuzxUtil.getObject(result, "data");
            if (!VtuzxUtil.isEmpty(stockAllocateList)) {
                for (Map<String,Object> skuData : stockAllocateList){
                    String googsNo = VtuzxUtil.getString(skuData,"goodsNo");
                    Double currentQuantity = VtuzxUtil.getDouble(skuData,"currentQuantity");
                    skuMap.put(googsNo,currentQuantity);
                }

                // 如果返回的数据超过 50 条，分页继续
                if (stockAllocateList.size() >= 50) {
                    Map<String, Object> nextPageMap = syncAllocation(stockNo, batchSkuList, pageIndex + 1);
                    skuMap.putAll(nextPageMap);
                }
            }
        }

        return skuMap;
    }

    /**
     * 根据拼接后字符串长度拆分List
     */
    private List<List<String>> splitListByStringLength(List<String> list, int maxLength, String delimiter) {
        List<List<String>> result = new ArrayList<>();
        List<String> temp = new ArrayList<>();
        int length = 0;

        for (String s : list) {
            if (s == null) continue;
            int extraLength = (temp.isEmpty() ? 0 : delimiter.length()) + s.length();
            if (length + extraLength > maxLength) {
                if (!temp.isEmpty()) {
                    result.add(new ArrayList<>(temp));
                    temp.clear();
                    length = 0;
                }
            }
            temp.add(s);
            length += extraLength;
        }

        if (!temp.isEmpty()) {
            result.add(temp);
        }

        return result;
    }


    /**
     * 逻辑删除调拨单信息
     * @param userId
     * @param userName
     * @param billNo
     */
    @Override
    public void deleteBainianAllocate(ObjectId userId, String userName, String billNo) {
        _logger.info(String.format("%s逻辑删除%s",userName,billNo));
        Criteria cond = Criteria.where("allocateNo").is(billNo);
        bainianAllocationDao.updateOne(cond,new Document("isUpload",true));
    }

    /**
     * 吉客云创建调拨单,从大连总仓外新工厂调的，从委外仓往新工厂调
     * @param userId
     * @param userName
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    public VtuzxMap createAllocationByAllocation(ObjectId userId, String userName, Map<String, Object> param) throws Exception {
        List<Map<String,Object>> dataList = VtuzxUtil.getObject(param,"detailList");
        List<Map<String,Object>> weiList = new ArrayList<>();//需要从委外仓调拨的
        List<Map<String,Object>> daList = new ArrayList<>();//需要从新工厂调拨的
        List<String> allocateNoList = new ArrayList<>();//调拨单号
        List<String> weiNoList = new ArrayList<>();//委外调拨单号
        List<String> daNoList = new ArrayList<>();//老工厂调拨单号
        for (Map<String,Object> data : dataList){
            Double weiUse = VtuzxUtil.getDouble(data,"weiUse");
            Double daUse = VtuzxUtil.getDouble(data,"daUse");
            String allocateNo = VtuzxUtil.getString(data,"allocateNo");
            if (weiUse > 0){
                weiList.add(data);
            }
            if (daUse > 0){
                daList.add(data);
            }
            if (!allocateNoList.contains(allocateNo)){
                allocateNoList.add(allocateNo);
            }
        }
        if (!VtuzxUtil.isEmpty(weiList)){
            for (Map<String,Object> data : weiList){
                String allocateNo = VtuzxUtil.getString(data,"allocateNo");
                if (!weiNoList.contains(allocateNo)){
                    weiNoList.add(allocateNo);
                }
            }
            //生成调拨单
            uploadJikeyunAllocationBill(userId,userName,weiList,"wei",weiNoList);

        }
        if (!VtuzxUtil.isEmpty(daList)){
            for (Map<String,Object> data : daList){
                String allocateNo = VtuzxUtil.getString(data,"allocateNo");
                if (!daNoList.contains(allocateNo)){
                    daNoList.add(allocateNo);
                }
            }
            //生成调拨单
            uploadJikeyunAllocationBill(userId,userName,daList,"da",daNoList);
        }
        //修改单据状态为已上传
        Criteria cond = Criteria.where("allocateNo").in(allocateNoList);
        bainianAllocationDao.updateMany(cond,new Document("isUpload",true));


        return null;
    }

    @Override
    public VtuzxMap getBainianAllocationLogList(ObjectId userId, Map<String, Object> param, int pageIndex, int pageSize) {
        String allocateNo = VtuzxUtil.getString(param, "allocateNo");
        Criteria cond = new Criteria();
        cond.and("isUpload").is(true);
        if (!VtuzxUtil.isEmpty(allocateNo)) {
            cond.and("allocateNo").regex(allocateNo);
        }

        VtuzxPage page = bainianAllocationDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> new VtuzxMap("id", VtuzxUtil.getString(doc, IVtuzxConst.Key__id))
                .append("allocateNo", VtuzxUtil.getString(doc, "allocateNo"))//单据类型
                .append("outWarehouseName", VtuzxUtil.getString(doc, "outWarehouseName"))
                .append("intWarehouseName", VtuzxUtil.getString(doc, "intWarehouseName"))
                .append("daAllocateNo", VtuzxUtil.getString(doc, "daAllocateNo"))
                .append("weiAllocationNo", VtuzxUtil.getString(doc, "weiAllocationNo"))
                .append("companyName", VtuzxUtil.getString(doc, "companyName"))
                .append("memo", VtuzxUtil.getString(doc, "memo")));

        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }
}
